w3resource logo
Python Exercises

Python: Find the nearest value from a given value in an array

Python NumPy: Random Exercise-9 with Solution

Write a Python program to find the nearest value from a given value in an array.

Sample Solution :-

Python Code :

import numpy as np
x = np.random.uniform(1, 12, 5)
v = 4
n = x.flat[np.abs(x - v).argmin()]
print(n)

Sample Output:

4.2507132388

Python Code Editor:

import numpy as np
x = np.random.uniform(1, 12, 5)
v = 4
n = x.flat[np.abs(x - v).argmin()]
print(n)

Improve this sample solution and post your code through Disqus