[Numpy-discussion] Assigning complex values to a real array

Dr. Phillip M. Feldman pfeldman@verizon....
Mon Dec 7 22:13:28 CST 2009

Robert Kern-2 wrote:
> <snip>
> Downcasting data is a necessary operation sometimes. We explicitly
> made a choice a long time ago to allow this.
> Robert Kern

This might be the time to recognize that that was a bad choice and reverse
it.  It is not clear to me why downcasting from complex to real sometimes
raises an exception, and sometimes doesn't.  Here are two examples where the
behavior of NumPy is inexplicably different:

Example #1:
IPython 0.10   [on Py 2.5.4]
[~]|1> z= zeros(3)
[~]|2> z[0]= 1+1J

TypeError: can't convert complex to float; use abs(z)

Example #2:

 from numpy import *
 q = ones(2,dtype=complex)*(1 + 1J)
 r = zeros(2,dtype=float)
 r[:] = q
 print 'q = ',q
 print 'r = ',r
 ### END OF CODE ###

 [~]|9> run err
 q =  [ 1.+1.j  1.+1.j]
 r =  [ 1.  1.]

In example #1, when we attempt to assign a complex value to a single element
of a float array, an exception is triggered.  In example #2, when we assign
the entire array (actually, a slice), the imaginary part is silently
discarded and we get a wrong result.  At a minimum, this inconsistency needs
to be cleared up.  My preference would be that the programmer should have to
explicitly downcast from complex to float, and that if he/she fails to do
this, that an exception be triggered.

Dr. Phillip M. Feldman
View this message in context: http://old.nabble.com/Assigning-complex-values-to-a-real-array-tp22383353p26688453.html
Sent from the Numpy-discussion mailing list archive at Nabble.com.

More information about the NumPy-Discussion mailing list