自己封装一个三维矢量的类,这个矢量可以是实数矢量,也可以是复数矢量,实现矢量的+-,点乘,叉乘,如果是实数矢量,实现两个矢量的夹角求解,投影长度求解等常规矢量的运算;
时间: 2024-12-04 10:24:43 浏览: 20
我可以帮你设计一个名为`Vector`的类,它包含属性用于存储三维矢量(x、y、z分量),支持实数和复数两种类型的表示。以下是基本的功能实现:
```python
import math
class Vector:
def __init__(self, x=0, y=0, z=0, is_complex=False):
self.x = x
self.y = y
self.z = z
self.is_complex = is_complex
# 实数矢量操作
def __add__(self, other):
if isinstance(other, Vector) and not self.is_complex and not other.is_complex:
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
else:
raise ValueError("Cannot add different vector types.")
def __sub__(self, other):
if isinstance(other, Vector) and not self.is_complex and not other.is_complex:
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
else:
raise ValueError("Cannot subtract different vector types.")
def dot_product(self, other):
if isinstance(other, Vector) and not self.is_complex and not other.is_complex:
return self.x * other.x + self.y * other.y + self.z * other.z
else:
raise ValueError("Dot product is only applicable for real vectors.")
def cross_product(self, other):
if isinstance(other, Vector) and not self.is_complex and not other.is_complex:
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:
raise ValueError("Cross product is only for real vector pairs.")
# 复数矢量操作
def complex_add(self, other):
if self.is_complex and other.is_complex:
real_part = self.x + other.x
imag_part = self.y + other.y
return Vector(real_part, imag_part, self.z + other.z, True)
else:
raise TypeError("Can only perform complex addition with another complex vector.")
# 实数矢量的特殊方法
def angle_between(self, other):
if not self.is_complex and not other.is_complex:
dot_product = self.dot_product(other)
magnitude1 = math.sqrt(self.x**2 + self.y**2 + self.z**2)
magnitude2 = math.sqrt(other.x**2 + other.y**2 + other.z**2)
if magnitude1 == 0 or magnitude2 == 0:
return 0
return math.degrees(math.acos(dot_product / (magnitude1 * magnitude2)))
else:
raise ValueError("Angle calculation is for real vectors only.")
def projection_length(self, onto):
if not self.is_complex and not onto.is_complex:
dot_product = self.dot_product(onto)
return abs(dot_product) / onto.magnitude()
else:
raise ValueError("Projection length can only be calculated for real vectors.")
@property
def magnitude(self):
return math.sqrt(self.x**2 + self.y**2 + self.z**2)
# 示例用法
v1 = Vector(1, 2, 3)
v2 = Vector(4, 5, 6)
print(v1.angle_between(v2)) # 计算两向量之间的角度
```
阅读全文