﻿ NumPy: Find the nearest value from a given value in an array - 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
```

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:

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Returns the symmetric difference between two iterables, without filtering out duplicate values:

Example:

```def tips_symmetric_difference(p, q):
_p, _q = set(p), set(q)
return [item for item in p if item not in _q] + [item for item in q if item not in _p]
print(tips_symmetric_difference([2, 4, 6], [2, 4, 8]))
```

Output:

```[6, 8]
```

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook