定义一个二维向量类Vector
时间: 2023-07-10 13:23:23 浏览: 61
好的,下面是一个基本的二维向量类Vector的定义,包含向量的x和y分量以及一些基本的向量运算方法:
```python
import math
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "Vector({}, {})".format(self.x, self.y)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Vector(self.x * other, self.y * other)
def __rmul__(self, other):
return Vector(self.x * other, self.y * other)
def __truediv__(self, other):
return Vector(self.x / other, self.y / other)
def __neg__(self):
return Vector(-self.x, -self.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self.__eq__(other)
def dot(self, other):
return self.x * other.x + self.y * other.y
def cross(self, other):
return self.x * other.y - self.y * other.x
def norm(self):
return math.sqrt(self.dot(self))
def normalize(self):
return self / self.norm()
def angle(self, other):
cos_theta = self.dot(other) / (self.norm() * other.norm())
return math.acos(cos_theta)
def rotate(self, angle):
x = self.x * math.cos(angle) - self.y * math.sin(angle)
y = self.x * math.sin(angle) + self.y * math.cos(angle)
return Vector(x, y)
```
使用示例:
```python
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)
print(v1 - v2)
print(v1 * 2)
print(2 * v1)
print(v1 / 2)
print(-v1)
print(v1.dot(v2))
print(v1.cross(v2))
print(v1.norm())
print(v1.normalize())
print(v1.angle(v2))
print(v1.rotate(math.pi / 2))
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)