四元数代码python
时间: 2023-11-08 16:04:55 浏览: 99
四元数法matlab代码-averaging-quaternions:用于正确平均多个四元数的Python函数
以下是 Python 中实现四元数的代码:
```python
class Quaternion:
def __init__(self, w=1.0, x=0.0, y=0.0, z=0.0):
self.w = w
self.x = x
self.y = y
self.z = z
def __mul__(self, other):
w = self.w * other.w - self.x * other.x - self.y * other.y - self.z * other.z
x = self.w * other.x + self.x * other.w + self.y * other.z - self.z * other.y
y = self.w * other.y - self.x * other.z + self.y * other.w + self.z * other.x
z = self.w * other.z + self.x * other.y - self.y * other.x + self.z * other.w
return Quaternion(w, x, y, z)
def __str__(self):
return f"{self.w} + {self.x}i + {self.y}j + {self.z}k"
```
其中,`w`、`x`、`y`、`z` 分别表示四元数的实部和虚部,`__mul__` 方法实现了四元数的乘法运算,`__str__` 方法用于打印四元数的值。
阅读全文