[Numpy-discussion] numarray: need Float32 abs from array of type na.Complex64 or na.Complex32

Todd Miller jmiller at stsci.edu
Thu Mar 2 07:14:03 CST 2006

Sebastian Haase wrote:
> Hi,
> I just was hunting a very strange bug: I got weird results .... anyway.
> I found that I was using this line of code:
> if img.type() in (na.Complex64, na.Complex32):
>      img = abs(na.asarray(img, na.Float32))
> Now I don't understand how this code worked at all ? But I only saw those 
> "weird results" after looking at the "dimmest corners" in my image and 
> otherwise all images looked O.K.
> The goal here was to get a single precision absolute for either a complex64 or 
> complex32 valued image array WITHOUT creating a temporary array.
This idea sounds inconsistent to me.  If the array is Complex64 and you 
pass it into asarray(,Float32),  you're going to get a temporary.   AND 
you're also truncating the imaginary part as you downcast to Float32... 
you're not getting a complex magnitude.

Since abs() transforms from complex to real,  you're going to get a 
temporary unless  you get a little fancy,  maybe like this:

na.abs(img, img.real)   # stores the abs() into the real component of 
the original array.  img.real is a view not a copy.
img.imag = 0               # optional step which makes the complex img 
array a real valued array with complex storage.
img = img.real             # just forget that img is using complex 

Note that img is now discontiguous since no copy was made and there are 
still interleaved 0-valued imaginary components.   So,  I think there 
are two points to avoiding a copy here: (1) use the optional ufunc 
output parameter  (2) store the abs() result into the .real view of the 
original complex array.
> My thinking was that:
> img = na.abs( na.asarray(img, na.Complex32) ) 
> would create a complete temporary version of img starts out being Complex64
> Is this really the case ?

More information about the Numpy-discussion mailing list