定义一个向量类,判断向量是否相等,并求模,加减乘除和向量积与数量积。用python
时间: 2023-09-05 16:07:06 浏览: 129
以下是一个基本的向量类的实现,包括判断向量相等、向量模、向量加减、向量乘除、向量积和数量积等操作:
```python
class Vector:
def __init__(self, lst):
self._values = list(lst)
def __repr__(self):
return "Vector({})".format(self._values)
def __str__(self):
return "({})".format(", ".join(str(e) for e in self._values))
def __len__(self):
return len(self._values)
def __getitem__(self, index):
return self._values[index]
def __setitem__(self, index, value):
self._values[index] = value
def __eq__(self, other):
if len(self) != len(other):
return False
for i in range(len(self)):
if self[i] != other[i]:
return False
return True
def __add__(self, other):
if len(self) != len(other):
raise ValueError("Vectors must be of the same length")
return Vector([self[i] + other[i] for i in range(len(self))])
def __sub__(self, other):
if len(self) != len(other):
raise ValueError("Vectors must be of the same length")
return Vector([self[i] - other[i] for i in range(len(self))])
def __mul__(self, other):
if isinstance(other, (int, float)):
return Vector([self[i] * other for i in range(len(self))])
elif isinstance(other, Vector):
if len(self) != len(other):
raise ValueError("Vectors must be of the same length")
return sum([self[i] * other[i] for i in range(len(self))])
else:
raise TypeError("Multiplication is only defined for scalar and vector values")
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
if isinstance(other, (int, float)):
return Vector([self[i] / other for i in range(len(self))])
else:
raise TypeError("Division is only defined for scalar values")
def cross(self, other):
if len(self) != 3 or len(other) != 3:
raise ValueError("Cross product is only defined for 3-dimensional vectors")
return Vector([
self[1] * other[2] - self[2] * other[1],
self[2] * other[0] - self[0] * other[2],
self[0] * other[1] - self[1] * other[0]
])
def dot(self, other):
return self * other
def norm(self):
return math.sqrt(sum([e ** 2 for e in self._values]))
```
使用示例:
```python
v1 = Vector([1, 2, 3])
v2 = Vector([1, 2, 3])
v3 = Vector([4, 5, 6])
print(v1 == v2) # True
print(v1 == v3) # False
print(v1 + v3) # Vector([5, 7, 9])
print(v1 - v3) # Vector([-3, -3, -3])
print(v1 * 2) # Vector([2, 4, 6])
print(v1 / 2) # Vector([0.5, 1.0, 1.5])
print(v1.dot(v3)) # 32
print(v1.cross(v3)) # Vector([-3, 6, -3])
print(v1.norm()) # 3.7416573867739413
```
阅读全文