w3resource

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

NumPy: Random Exercise-9 with Solution

Write a NumPy 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

Pictorial Presentation:

NumPy Random: Find the nearest value from a given value in an array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to create a random vector of size 10 and sort it.
Next: Write a NumPy program to check two random arrays are equal or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Performs right-to-left function composition:

Example:

from functools import reduce

def tips_compose(*fns):
  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
add6 = lambda x: x + 6
multiply = lambda x, y: x * y
multiply_and_add_6 = tips_compose(add6, multiply)

print(multiply_and_add_6(10, 3))

Output:

36