我试图实现我的自定义四元数数据类型,它有 4 个成员:w、x、y、z。我找到了官方示例代码: https ://github.com/numpy/numpy-dtypes/tree/master/npytypes/quaternion
我通过以下方式测试了这个实现:
import numpy as np
import npytypes.quaternion
a = np.zeros((2, 2), dtype=np.float).astype(np.quaternion)
print(a)
print(a[0][0].w) # correct, get 0.0
print(a.w) # wrong, AttributeError: 'numpy.ndarray' object has no attribute 'w'
我得到了:
[[quaternion(0, 0, 0, 0) quaternion(0, 0, 0, 0)]
[quaternion(0, 0, 0, 0) quaternion(0, 0, 0, 0)]]
0.0
Traceback (most recent call last):
File "e:/..../test.py", line 7, in <module>
print(a.w)
AttributeError: 'numpy.ndarray' object has no attribute 'w'
我的期望是这样的:
>>> a.w
array([[0.0, 0.0], [0.0, 0.0]], dtype=np.float)
我的问题是如何修改该代码以实现这一目标?
np.complex
做得很好:
>>> import numpy as np
>>> a = np.random.rand(2, 3).astype(np.complex)
>>> a
array([[0.94226049+0.j, 0.71994713+0.j, 0.718848 +0.j],
[0.57285105+0.j, 0.35576711+0.j, 0.51016149+0.j]])
>>> a.real
array([[0.94226049, 0.71994713, 0.718848 ],
[0.57285105, 0.35576711, 0.51016149]])
>>> a.real.dtype
dtype('float64')