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

Question:

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 it the results are different when try to deal with numpy array.

Asked By: Xianxu Hou

||

Answers:

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

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

Modifying an array inplace — for example, with a /= 2.0 — does not change
the dtype. So the result contains ints.

In contrast, a/2.0 "upcasts" the resultant array to float since the divisor is
a float.


If you start with an array of floating-point dtype, then both operations yield 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])
Answered By: unutbu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.