python-3.xnumpynumpy-slicingnumpy-indexing

Condition indexing numpy array of floats


import numpy as np

n = 10
xmin = 0
xmax = 1
dx = 1/n
x = np.arange(xmin-dx, xmax + 2*dx, dx)
print(x)
print(x <= 0.3)

The output of this code is following :

[-0.1  0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9  1.   1.1]
[ True  True  True  True False False False False False False False False
 False]

Why the element in array with value 0.3 is not smaller or equal than 0.3? ​I tried the same with other comparasions and i saw that -0.1 <= -0.1 and 0.1 <= 0.1 while 0.2 is not less or equal 0.2. Really do not understand what is happening here.


Solution

  • I got it. Never compare float numbers, because of round-off error. This will work:

    print(x <= 0.3 + np.finfo(np.float64).eps)