[Numpy-discussion] Nasty bug using pre-initialized arrays

Stuart Brorson sdb@cloud9....
Fri Jan 4 15:08:54 CST 2008

NumPy gurus --

I just discovered this today.  It looks like a bug to me.  Please
flame me mercilessly if I am wrong!  :-)

Sometimes you need to initialize an array using zeros() before doing
an assignment to it in a loop.  If you assign a complex value to the
initialized array, the imaginary part of the array is dropped.  Does
NumPy do a silent type-cast which causes this behavior?  Is this
typecast a feature?

Below I attach a session log showing the bug.  Note that I have boiled
down my complex code to this simple case for ease of comprehension.  [1] 
I will also input this bug into the tracking system.

By the way, this is NumPy 1.0.4:

In [39]: numpy.__version__
Out[39]: '1.0.4'


Stuart Brorson
Interactive Supercomputing, inc.
135 Beaver Street | Waltham | MA | 02452 | USA

----------------------  <session log>  --------------------

In [29]: A = numpy.random.rand(4) + 1j*numpy.random.rand(4)

In [30]: B = numpy.zeros((4))

In [31]:

In [31]: for i in range(4):
    ....:       B[i] = A[i]

In [32]: A
array([ 0.12150180+0.00577893j,  0.39792515+0.03607227j,
         0.61933379+0.04506978j,  0.56751678+0.24576083j])

In [33]: B
Out[33]: array([ 0.1215018 ,  0.39792515,  0.61933379,  0.56751678])

-----------------------  </session log>  -------------------

[1]  Yes, I know that I should use vectorized code as often as
possible, and that this example is not vectorized.  This is a simple
example illustrating the problem.  Moreover, many times the
computation you wish to perform can't easily be vectorized, leaving
the nasty old for loop as the only choice......

More information about the Numpy-discussion mailing list