[Numpy-tickets] [NumPy] #640: Index assignment into pre-allocated array does silent type cast, causing user confusion (or worse)

NumPy numpy-tickets@scipy....
Fri Jan 4 15:12:57 CST 2008

#640: Index assignment into pre-allocated array does silent type cast, causing
user confusion (or worse)
 Reporter:  brorson     |       Owner:  somebody
     Type:  defect      |      Status:  new     
 Priority:  normal      |   Milestone:  1.0.5   
Component:  numpy.core  |     Version:  none    
 Severity:  normal      |    Keywords:          
 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......

Ticket URL: <http://scipy.org/scipy/numpy/ticket/640>
NumPy <http://projects.scipy.org/scipy/numpy>
The fundamental package needed for scientific computing with Python.

More information about the Numpy-tickets mailing list