In python the result of a = 2.0 and a = a / 2.0 are not the same
In [67]: import numpy as np
In [68]: a = np.arange(10)
In [69]: b = a.copy()
In [70]: a /= 2.0
In [71]: a
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 the results are different when you try to figure out a numpy array.
+3
source to share
1 answer
a = np.arange(10)
has an integer dtype.
>>> np.arange(10).dtype
dtype('int64')
Changing the array in place - for example with a /= 2.0
- does not change the dtype. So the result contains ints.
In contrast, a/2.0
"lifts" the resulting array to float, since the divisor is equal to the float.
If you start with a floating point dtype array, then both operations give the same result:
In [12]: a = np.arange(10, dtype='float')
In [13]: b = a.copy()
In [14]: a /= 2.0
In [15]: a
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])
+10
source to share