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 arrayarr
, which in this case isnp.float32
. On the other hand, with something likearr > arr2
, with both arguments nonscalar arrays, they will use a common data type. That's why (arr > np.array([np.pi]))[3154950]
returnsTrue
.