定义一个向量类,判断向量是否相等,并求模,加减乘除和向量积与数量积。用python在pycharm钟云行
时间: 2023-07-16 10:16:48 浏览: 87
可以使用以下代码实现向量类:
```python
import math
class Vector:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.z == other.z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, other):
if isinstance(other, Vector):
return Vector(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
else:
return Vector(self.x * other, self.y * other, self.z * other)
def __truediv__(self, other):
return Vector(self.x / other, self.y / other, self.z / other)
def __abs__(self):
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def angle(self, other):
cos = self.dot(other) / (abs(self) * abs(other))
return math.acos(cos)
```
这个向量类包含了向量的基本操作,包括相等判断、加减乘除、求模、向量积与数量积。
以下是使用向量类的示例:
```python
v1 = Vector(1, 2, 3)
v2 = Vector(4, 5, 6)
print(v1 == v2) # False
v3 = v1 + v2
print(v3.x, v3.y, v3.z) # 5 7 9
v4 = v1 - v2
print(v4.x, v4.y, v4.z) # -3 -3 -3
v5 = v1 * 2
print(v5.x, v5.y, v5.z) # 2 4 6
v6 = v1 / 2
print(v6.x, v6.y, v6.z) # 0.5 1.0 1.5
print(abs(v1)) # 3.7416573867739413
v7 = v1 * v2
print(v7.x, v7.y, v7.z) # -3 6 -3
dot_product = v1.dot(v2)
print(dot_product) # 32
angle = v1.angle(v2)
print(angle) # 0.2257261285527342
```
阅读全文