I need to find the index of the first element in an array, that is close to a float within a given tolerance.
I can do this with a for block:
import numpy as np
# Define array of floats
a = np.random.uniform(0., 10., 10.)
# Float to search, and tolerance.
val, tol = 6.87, 0.1
for i, _ in enumerate(a):
if np.isclose(_, val, tol):
print('Index is: {}'.format(i))
break
but I was wondering if there might be a one-liner solution using some numpy function.
Notice that I'm interested in the index of the first element that is close to val, no matter that there might be closer elements further down the a array. The solutions I've found are interested in the index of the nearest value, no matter where it is located within the array.