Numpy array integer / float division

11,128

The problem with a /= 10.0 is that it modifies the array in place, and it won't change the the dtype of the array, so all the floats are converted to integers. On the other hand a = a / 10.0 created a new array, and the type can be changed if a new array is being created.

From docs:

Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints):

Share:
11,128

Related videos on Youtube

Sebastian
Author by

Sebastian

Updated on June 04, 2022

Comments

  • Sebastian
    Sebastian almost 2 years

    I found the following behaviour in Python/NumPy somewhat strange:

    In [51]: a = np.arange(10, 20)
    In [52]: a = a / 10.0
    In [53]: a
    Out[53]: array([ 1. ,  1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9])
    
    In [54]: a = np.arange(10, 20)
    In [55]: a /= 10.0
    In [56]: a
    Out[56]: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
    

    I felt that a=a/10.0 and a/=10.0 should return the same result. Is this intended and documented somewhere?

  • Yuxiang Wang
    Yuxiang Wang about 10 years
    +1 for the great answer. Personally, when I tried to generate double floats, I always used np.arange(10., 20.) to be safe.