自定义三维向量类,模拟两个三维向量的加减乘除等运算 python
时间: 2024-02-20 17:57:58 浏览: 82
用Python自定义三维向量类,实现加减乘除等运算
好的,我可以帮你实现一个自定义的三维向量类,并且重载加减乘除等运算符,以下是示例代码:
```python
import math
class Vector3:
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f"Vector3({self.x}, {self.y}, {self.z})"
def __add__(self, other):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar):
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
def __truediv__(self, scalar):
return Vector3(self.x / scalar, self.y / scalar, self.z / scalar)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
return Vector3(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
def magnitude(self):
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def normalize(self):
mag = self.magnitude()
if mag > 0:
self.x /= mag
self.y /= mag
self.z /= mag
# 测试代码
v1 = Vector3(1, 2, 3)
v2 = Vector3(4, 5, 6)
print(v1 + v2) # Vector3(5, 7, 9)
print(v1 - v2) # Vector3(-3, -3, -3)
print(v1 * 2) # Vector3(2, 4, 6)
print(v2 / 2) # Vector3(2.0, 2.5, 3.0)
print(v1.dot(v2)) # 32
print(v1.cross(v2)) # Vector3(-3, 6, -3)
v3 = Vector3(3, 0, 0)
v3.normalize()
print(v3) # Vector3(1.0, 0.0, 0.0)
```
这是一个简单的示例,你可以根据需要添加更多的操作符重载和方法。
阅读全文