Array comparison not matching elementwise comparison in numpy Array comparison not matching elementwise comparison in numpy numpy numpy

Array comparison not matching elementwise comparison in numpy


The problem is due to accuracy of np.float32 vs np.float64.

Use np.float64 and you will not see a problem:

import numpy as nparr = np.array([3.1415927], dtype=np.float64)print((arr > np.pi)[0])  # Trueprint(arr[0] > np.pi)    # True

As @WarrenWeckesser comments:

It involves how numpy decides to cast the arguments of its operations. Apparently, with arr > scalar, the scalar is converted to the same type as the array arr, which in this case is np.float32. On the other hand, with something like arr > arr2, with both arguments nonscalar arrays, they will use a common data type. That's why (arr > np.array([np.pi]))[3154950] returns True.

Related github issue