设计一个三维向量类 Vector3D,包含三维向量的一些基本运算,如加法、减法以及点乘、叉乘。如v1= (1,2,3), v2= (4,5,6),
时间: 2024-02-27 19:53:23 浏览: 95
AttitudeControl.zip_32H_叉乘_向量点乘_向量运算
好的,我可以设计一个如下的 Vector3D 类:
```python
class Vector3D:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, other):
if isinstance(other, (int, float)):
return Vector3D(self.x * other, self.y * other, self.z * other)
elif isinstance(other, Vector3D):
return self.dot(other)
else:
raise TypeError("unsupported operand type(s) for *: '{}' and '{}'".format(type(self).__name__, type(other).__name__))
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
if isinstance(other, (int, float)):
return Vector3D(self.x / other, self.y / other, self.z / other)
else:
raise TypeError("unsupported operand type(s) for /: '{}' and '{}'".format(type(self).__name__, type(other).__name__))
def __repr__(self):
return "Vector3D({}, {}, {})".format(self.x, self.y, self.z)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
return Vector3D(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
```
其中,加法、减法、点乘和叉乘分别通过 `__add__`、`__sub__`、`dot` 和 `cross` 方法实现。而乘法和除法则分别通过 `__mul__`、`__rmul__` 和 `__truediv__` 方法实现,其中乘法支持向量和标量的乘法,以及向量和向量的点乘。最后,`__repr__` 方法用于返回向量的字符串表示。
现在,我们可以使用这个 Vector3D 类来计算两个向量的加法、减法、点乘和叉乘:
```python
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(4, 5, 6)
v3 = v1 + v2
print(v3) # 输出:Vector3D(5, 7, 9)
v4 = v1 - v2
print(v4) # 输出:Vector3D(-3, -3, -3)
dot = v1.dot(v2)
print(dot) # 输出:32
cross = v1.cross(v2)
print(cross) # 输出:Vector3D(-3, 6, -3)
```
希望这个 Vector3D 类能够满足你的要求。如果还有其他问题,请随时问我。
阅读全文