w3resource

NumPy: Find the closest value (to a given scalar) in an array

NumPy: Random Exercise-15 with Solution

Write a NumPy program to find the closest value (to a given scalar) in an array.

Sample Solution:

Python Code:

# Importing the NumPy library as np
import numpy as np

# Creating an array 'x' containing numbers from 0 to 99 using arange() function
x = np.arange(100)

# Displaying the original array 'x'
print("Original array:")
print(x)

# Generating a random floating-point number 'a' between 0 and 100
a = np.random.uniform(0, 100)

# Displaying the value used for comparison
print("Value to compare:")
print(a)

# Finding the index of the element in array 'x' closest to the generated value 'a'
index = (np.abs(x - a)).argmin()

# Displaying the element in 'x' that is closest to the generated value 'a'
print(x[index]) 

Sample Output:

Original array:                                                        
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24                                                                   
 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 4 8 49                                                                   
 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 7 3 74                                                                   
 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 9
8 99]                                                                  
Value to compare:                                                      
38.09066280756759                                                      
38   

Explanation:

In the above exercise –

x = np.arange(100): This line generates a 1D array of integers from 0 to 99 (inclusive).

a = np.random.uniform(0, 100): This line generates a random float number between 0 and 100 (not including 100).

index = (np.abs(x - a)).argmin(): This line calculates the absolute difference between the random float number a and each integer in the array x, and then finds the index of the minimum absolute difference. This index corresponds to the closest integer value to a in the array x.

print(x[index]): This line prints the closest integer value to the random float number a by indexing the array x with the calculated index.

Python-Numpy Code Editor:

Previous: Write a NumPy program to convert cartesian coordinates to polar coordinates of a random 10x3 matrix representing cartesian coordinates.
Next: Write a NumPy program to get the n largest values of an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.