Reputation: 5646
I often need to find a smaller array xs
in a larger array X
. However, since these arrays are the result of floating point arithmetic, exact comparison fails miserably. How can I fix this? MRE:
import numpy as np
np.random.seed(2021)
X = np.random.rand(20,4,3)
idx = 4
xs = X[4,3]
idx_x = np.where((X[:,3,:] == xs).all(axis=1))[0]
assert idx_x == 4 # pass
xs = X[4,3] + 1e-9
idx_x = np.where((X[:,3,:] == xs).all(axis=1))[0]
assert idx_x == 4, "exact equality fails" # fail
How can I modify the code so that it checks for approximate, rather than exact, inequality?
Upvotes: 1
Views: 25