[Numpy-discussion] Python objects in Numpy: compatibility issues with methods and functions

Felix Richter felix@physik3.uni-rostock...
Wed Sep 17 05:44:51 CDT 2008

Hi all,

for my calculations, I need multi-precision arithmetics. For this, I use the 
wonderful Python-only mpmath (http://code.google.com/p/mpmath/) and store and 
handle my data in Numpy arrays. I thus have Numpy arrays with dtype=object 
holding mpmath objects.

Now, some of the array operations that make Numpy such an invaluable tool work 
(like adding to arrays or even the dot product!), other silently fail 
(like .imag or .conj()). I added an example session below. 

What happens if .imag is evaluated on a Numpy array? How does Numpy determine 
the imaginary part of an object dtype? Is this propagated to the elements and 
are there some hooks?

(The case of conj is quite confusing, as m2.conj() silently fails but 
np.conj(m2) works perfectly.)

In other words: What interface must a Python class provide to ensure that  
Numpy array operations work? I guess this is somewhat close to what T.J. 
Alumbaugh asked some days ago.

Thanks for any hints,


In [1]:import numpy as np

In [2]:import mpmath

In [3]:m2 = np.array([mpmath.mpc(1+2j),mpmath.mpc(2+3j)])

In [4]:m2
Out[4]:array([(1.0 + 2.0j), (2.0 + 3.0j)], dtype=object)

In [5]:m2.imag
Out[5]:array([0, 0], dtype=object)

In [6]:m2[0].imag

In [7]:m2.conj()
Out[7]:array([(1.0 + 2.0j), (2.0 + 3.0j)], dtype=object)

In [8]:m2[0].conj()
AttributeError                            Traceback (most recent call last)
AttributeError: 'mpc' object has no attribute 'conj'

In [10]:np.conj(m2[0])
Out[10]:mpc(real='1.0', imag='-2.0')

In [11]:np.conj(m2)
Out[11]:array([(1.0 - 2.0j), (2.0 - 3.0j)], dtype=object)

More information about the Numpy-discussion mailing list