1

我试图实现我的自定义四元数数据类型,它有 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')
4

1 回答 1

1

您可能认为复杂 dtype 的数组具有额外的属性,但这可能是因为您没有尝试访问arr.real或访问arr.imag非复杂 dtype 的数组。有用。这些属性并不是复杂数据类型特有的——它们是 NumPy 数组的基本功能。(此外,np.complex它只是常规 Pythoncomplex类型的向后兼容性别名 - 当您指定complex为 dtype 时,NumPy 会自动将其解释为请求 NumPy 的 complex128 dtype。)

np.ndarray对您正在尝试的内容没有任何支持。如果你真的想要,你可以子类np.ndarray化,但这会变得混乱,并且对常规数组没有帮助。

于 2020-03-28T10:02:27.483 回答