Why Numpy treats a+=b and a=a+b differently

后端 未结 2 444
挽巷
挽巷 2021-01-03 19:53

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,         


        
2条回答
  •  悲哀的现实
    2021-01-03 20:37

    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+b creates a brand new array for the sum, and rebinds a to point to this new array; this increases the amount of storage used for the operation.

    To quote the documentation:

    Warning: In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore, for mixed precision calculations, A {op}= B can be different than A = A {op} B. For example, suppose a = ones((3,3)). Then, a += 3j is different than a = a + 3j: while they both perform the same computation, a += 3 casts the result to fit back in a, whereas a = a + 3j re-binds the name a to the result.

    Finally, if you're wondering why a was an integer array in the first place, consider the following:

    In [3]: np.arange(5).dtype
    Out[3]: dtype('int64')
    
    In [4]: np.arange(5.0).dtype
    Out[4]: dtype('float64')
    

提交回复
热议问题