w3resource

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


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

Sample Solution :

Python Code :

# Importing the NumPy library as np
import numpy as np

# Generating an array of 5 random numbers between 1 and 12 using np.random.uniform()
x = np.random.uniform(1, 12, 5)

# Setting a value 'v' to find the number closest to it in the array 'x'
v = 4

# Finding the value 'n' in 'x' that is closest to 'v'
# Using np.abs(x - v).argmin() to get the index of the element in 'x' closest to 'v'
# Accessing the element using x.flat[index] to get the closest value 'n'
n = x.flat[np.abs(x - v).argmin()]

# Printing the value 'n' that is closest to 'v'
print(n) 

Sample Output:

4.2507132388

Explanation:

In the above exercise –

x = np.random.uniform(1, 12, 5): This line creates a 1D array x with 5 random numbers between 1 and 12 using the np.random.uniform() function. The input values 1 and 12 specify the lower and upper boundaries of the uniform distribution, and 5 is the size of the output array.

v = 4: This line assigns 4 to the variable v.

n = x.flat[np.abs(x - v).argmin()]: This line computes the closest element in the array x to the value v and assigns it to the variable n. The code performs the following operations:

  • x - v: Calculates the difference between each element in the array x and the value v.
  • np.abs(x - v): Returns the absolute value of the differences calculated in the previous step.
  • np.abs(x - v).argmin(): Finds the index of the minimum value in the array of absolute differences.
  • x.flat[np.abs(x - v).argmin()]: Uses the index found in the previous step to access the corresponding element in the flattened (1D) version of the array x and assigns it to the variable n.

print(n): Finally print() prints the value of the variable n.

Pictorial Presentation:

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

Python-Numpy Code Editor: