[Numpy-discussion] Assigning complex value to real array

Charles R Harris charlesr.harris@gmail....
Thu Oct 7 00:31:20 CDT 2010

On Wed, Oct 6, 2010 at 11:07 PM, Andrew P. Mullhaupt

> I came across this gem yesterday
> >>> from numpy import *
> >>> R = ones((2))
> >>> R[0] = R[0] * 1j
> >>> R
> ...array([ 0., 1.])
> >>> R = ones((2), 'complex')
> >>> R[0] = R[0] * 1j
> >>> R
> array([ 0.+1.j, 1.+0.j])" and I read that this behavior is actually
> intended for some reason about how Python wants relations between types to
> be such that this mistake is unavoidable.
It's because an element of a real array only has space for a real and you
can't fit a complex in there. Some other software which is less strict about
types may allow such things, but it comes at a cost.

> So can we have a new abstract floating type which is a complex, but is
> implemented so that the numbers where the imaginary part is zero represent
> and operate on that imaginary part implicitly? By containing all these
> semantics within one type, then presumably we avoid problems with ideas
> relationships between types.
Short answer: no. If you want complex just use a complex array. Changing
types like you propose would require making a new copy or reserving space
ahead of time, which would be wasteful. It could also be done with lists or
objects, but then you would lose speed. Newer versions of numpy will warn
you that the imaginary part is going to be discarded in your first example.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20101006/6d637858/attachment.html 

More information about the NumPy-Discussion mailing list