Is the following numpy behavior intentional or is it a bug?
from numpy import *
a = arange(5)
a = a+2.3
print 'a = ', a
# Output: a = 2.3, 3.3, 4.3, 5.3, 6.3
a = arange(5)
a += 2.3
print 'a = ', a
# Output: a = 2, 3, 4, 5, 6
Python version: 2.7.2, Numpy version: 1.6.1
That’s intentional.
The
+=operator preserves the type of the array. In other words, an array of integers remains an array of integers.This enables NumPy to perform the
+=operation using existing array storage. On the other hand,a=a+bcreates a brand new array for the sum, and rebindsato point to this new array; this increases the amount of storage used for the operation.To quote the documentation:
Finally, if you’re wondering why
awas an integer array in the first place, consider the following: