I was trying to implement my custom quaternion datatype which has 4 members: w, x, y, z. And I found the official example code: https://github.com/numpy/numpy-dtypes/tree/master/npytypes/quaternion
I tested this implementation by following:
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'
And I got:
[[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'
What I expect was like:
>>> a.w
array([[0.0, 0.0], [0.0, 0.0]], dtype=np.float)
And my question is that how can I modify that code to achive this goal?
np.complex did it well:
>>> 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')
You might think arrays of complex dtype have extra attributes, but that's probably because you haven't tried to access
arr.realorarr.imagon an array of non-complex dtype. It works. Those attributes aren't something specific to complex dtypes - they're baseline NumPy array functionality. (Also,np.complexis just a backwards compatibility alias for the regular Pythoncomplextype - when you specifycomplexas a dtype, NumPy will automatically interpret that as requesting NumPy's complex128 dtype.)np.ndarraydoes not have any support for what you're attempting. You could subclassnp.ndarrayif you really wanted, but that gets messy and wouldn't help with regular arrays.