How to Find the Closest Value in an Array Using Python?

In this tutorial, I will explain how to find the closest value in an array using Python. As a data scientist working with large datasets, I often need to find the nearest value to a given target within an array. In this article, we will explore different approaches to solve this problem using Python and the NumPy library with examples.

Read How to Write an Array to a File in Python?

Problem Statement

Let us say are working on a project to help a restaurant chain in the USA optimize its delivery routes. Each restaurant has its coordinates stored in a Python array. Given a customer’s location, you need to find the nearest restaurant to dispatch the delivery driver.

Check out How to Remove Duplicates from a Sorted Array in Python

Approach 1: Linear Search

The simplest approach to find the closest value in an array is to perform a linear search.

Here’s an example implementation in Python:

def find_nearest_value(arr, target):
    min_diff = float('inf')
    closest_value = None
    for num in arr:
        diff = abs(num - target)
        if diff < min_diff:
            min_diff = diff
            closest_value = num
    return closest_value

Let’s say we have an array of restaurant coordinates:

restaurant_coords = [37.7749, 40.7128, 34.0522, 47.6062, 29.7604]

The customer’s location is at latitude 38.9072. We can find the nearest restaurant like this:

customer_location = 38.9072
nearest_restaurant = find_nearest_value(restaurant_coords, customer_location)
print(f"The nearest restaurant is at latitude: {nearest_restaurant}")

Output:

The nearest restaurant is at latitude: 37.7749

I executed the above example code and added its screenshot below.

Find the Closest Value in an Array Using Python

The linear search approach is simple to understand and implement. However, it has a time complexity of O(n), where n is the size of the array. This means that as the array size grows, the search time increases linearly, which can be inefficient for large datasets.

Read How to Iterate Through a 2D Array in Python

Approach 2: Binary Search

A more efficient approach to find the closest value in a sorted array is to use binary search. Binary search has a time complexity of O(log n), which makes it much faster than linear search for large arrays.

Here’s an example implementation using Python:

def find_nearest_value_binary_search(arr, target):
    arr.sort()
    left = 0
    right = len(arr) - 1

    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return arr[mid]
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    if left == len(arr) or (target - arr[right] < arr[left] - target):
        return arr[right]
    else:
        return arr[left]

Using the same restaurant coordinates array:

restaurant_coords = [37.7749, 40.7128, 34.0522, 47.6062, 29.7604]

We can find the nearest restaurant to the customer’s location (38.9072) using binary search:

customer_location = 38.9072
nearest_restaurant = find_nearest_value_binary_search(restaurant_coords, customer_location)
print(f"The nearest restaurant is at latitude: {nearest_restaurant}")

Output:

The nearest restaurant is at latitude: 37.7749

I executed the above example code and added its screenshot below.

How to Find the Closest Value in an Array Using Python

Binary search provides a more efficient solution compared to linear search, especially for large sorted arrays.

Check out How to Distinguish Between Arrays and Lists in Python

Using NumPy

NumPy is a useful library for numerical computing in Python. It provides optimized functions for array operations, including finding the nearest value. Let’s see how we can use NumPy to solve our problem:

import numpy as np

def find_nearest_value_numpy(arr, target):
    arr = np.array(arr)
    idx = np.abs(arr - target).argmin()
    return arr[idx]

Using NumPy, we can find the nearest restaurant as follows:

restaurant_coords = [37.7749, 40.7128, 34.0522, 47.6062, 29.7604]
customer_location = 38.9072
nearest_restaurant = find_nearest_value_numpy(restaurant_coords, customer_location)
print(f"The nearest restaurant is at latitude: {nearest_restaurant}")

Output:

The nearest restaurant is at latitude: 37.7749

I executed the above example code and added its screenshot below.

How to Find the Closest Value in an Array Using Python Using NumPy

In this approach, we first convert the input array to a NumPy array using np.array(). Then, we use the np.abs() function to calculate the absolute differences between each element and the target value. The argmin() function returns the index of the minimum value in the resulting array of absolute differences. Finally, we return the element at that index, which represents the closest value.

Read How to Append to an Array in Python

Conclusion

In this tutorial, we explored different approaches to find the closest value in an array using Python, We also discussed the problem statement to have a better understanding. Our first approach is by linear search, and the second is by binary search, I also explained how to achieve this task using NumPy.

I hope this helped you to understand how to find the closest value in an array using Python.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.