So this recipe is a short example on how to find the nearest value from a given value in an array. Let's get started.
import numpy as np
Let's pause and look at these imports. Numpy is generally helpful in data manipulation while working with arrays. It also helps in performing mathematical operation.
def find_nearest(array, value): idx = (np.abs(array - value)).argmin() return array[idx]
We have a defined find_nearest function. It first subtracts the given value from all the elements of array. Then, finds the argument of closest value by taking the absolute value of all elements.
array = np.random.random(10) print(array) value = 0.5 print(find_nearest(array, value))
Here we define a random array and thereby find the closest value to 0.5
Once we run the above code snippet, we will see:
[0.91099284 0.4100222 0.26885347 0.0256024 0.10999511 0.11454188 0.79332232 0.71090965 0.3848031 0.82222392] 0.4100222047688208