numpy - In python the result of a /= 2.0 and a = a / 2.0 are not the same -


in [67]: import numpy np in [68]: = np.arange(10) in [69]: b = a.copy() in [70]: /= 2.0 in [71]: out[71]: array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]) in [72]: b = b / 2.0 in [73]:  in [73]: b out[73]: array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5]) 

i don't know why results different when try deal numpy array.

a = np.arange(10) has integer dtype.

>>> np.arange(10).dtype dtype('int64') 

modifying array inplace -- example, a /= 2.0 -- not change dtype. result contains ints.

in contrast, a/2.0 "upcasts" resultant array float since divisor float.


if start array of floating-point dtype, both operations yield same result:

in [12]: = np.arange(10, dtype='float')  in [13]: b = a.copy()  in [14]: /= 2.0  in [15]: out[15]: array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5])  in [16]: b = b / 2.0  in [17]: b out[17]: array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5]) 

Comments