设计一个三维向量类Vector3D,包含三维向量的一些基本运算,如加法、减法以及点乘、叉乘。如v1 = (1, 2, 3),v2 = (4, 5, 6)
时间: 2024-03-02 17:48:45 浏览: 30
好的,我可以为您设计一个三维向量类Vector3D。以下是示例代码:
```python
import math
class Vector3D:
def __init__(self, x=0, y=0, z=0):
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 dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
x = self.y * other.z - self.z * other.y
y = self.z * other.x - self.x * other.z
z = self.x * other.y - self.y * other.x
return Vector3D(x, y, z)
def length(self):
return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)
def normalize(self):
length = self.length()
if length == 0:
return Vector3D()
else:
return Vector3D(self.x/length, self.y/length, self.z/length)
def __str__(self):
return "Vector3D({}, {}, {})".format(self.x, self.y, self.z)
```
您可以使用以下代码进行测试:
```python
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(4, 5, 6)
v3 = v1 + v2
print(v3)
v4 = v1 - v2
print(v4)
dot_product = v1.dot(v2)
print(dot_product)
cross_product = v1.cross(v2)
print(cross_product)
length = v1.length()
print(length)
normalized = v1.normalize()
print(normalized)
```
输出结果:
```
Vector3D(5, 7, 9)
Vector3D(-3, -3, -3)
32
Vector3D(-3, 6, -3)
3.7416573867739413
Vector3D(0.2672612419124244, 0.5345224838248488, 0.8017837257372732)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)