python numpy find nearest value

Solutions on MaxInterview for python numpy find nearest value by the best coders in the world

showing results for - "python numpy find nearest value"
Johan
10 Jan 2018
1import numpy as np
2def find_nearest(array, value):
3    array = np.asarray(array)
4    idx = (np.abs(array - value)).argmin()
5    return array[idx]
6
7array = np.random.random(10)
8print(array)
9# [ 0.21069679  0.61290182  0.63425412  0.84635244  0.91599191  0.00213826
10#   0.17104965  0.56874386  0.57319379  0.28719469]
11
12value = 0.5
13
14print(find_nearest(array, value))
15# 0.568743859261
16