Calculate the Euclidean distance using NumPy
Euclidean distance is the shortest between the 2 points irrespective of the dimensions. In this article to find the Euclidean distance, we will use the NumPy library. This library used for manipulating multidimensional array in a very efficient way. Let's discuss a few ways to find Euclidean distance by NumPy library.
Using np.linalg.norm()
np.linalg.norm() function computes the norm (or magnitude) of a vector, which in the case of the difference between two points, gives us the Euclidean distance. It's a simple and efficient way to find the distance.
import numpy as np
p1 = np.array((1, 2, 3))
p2 = np.array((1, 1, 1))
d = np.linalg.norm(p1 - p2)
print(d)
Output
2.23606797749979
Explanation: We subtract p2 from p1 to get the difference vector (0, 1, 2). Then, np.linalg.norm(p1 - p2) directly calculates the Euclidean distance by finding the magnitude of the difference vector.
Using **
Here, we're manually calculating the Euclidean distance by summing the squares of the differences between corresponding coordinates and then taking the square root of that sum. It's a more "hands-on" approach compared to np.linalg.norm() but is functionally identical.
import numpy as np
p1 = np.array((1, 2, 3))
p2 = np.array((1, 1, 1))
d = np.sqrt(np.sum((p1 - p2)**2))
print(d)
Output
2.23606797749979
Explanation: (p1 - p2)**2 squares each element of the difference vector. np.sum() adds up these squared values (0 + 1 + 4 = 5).
Using np.einsum()
np.einsum() function compute the dot product of the difference vector with itself, effectively squaring and summing the differences. While efficient for complex calculations, it may be overkill for simple distance computation.
import numpy as np
p1 = np.array((1, 2, 3))
p2 = np.array((1, 1, 1))
d = np.sqrt(np.einsum('i,i->', p1 - p2, p1 - p2))
print(d)
Output
2.23606797749979
Explanation: First, we subtract p2 from p1 to get the difference vector (0, 1, 2). Then, np.einsum('i,i->', p1 - p2, p1 - p2) calculates the dot product of this vector with itself, summing the squared differences (0 + 1 + 4 = 5).
Using np.dot()
np.dot() function computes the dot product of the difference vector with itself, effectively summing the squared differences. Applying np.sqrt() then gives the Euclidean distance between the two points.
import numpy as np
p1 = np.array((1, 2, 3))
p2 = np.array((1, 1, 1))
d = np.sqrt(np.dot(p1 - p2, p1 - p2))
print(d)
Output
2.23606797749979
Explanation: This code calculates the difference vector (0, 1, 2) and then uses np.dot() to compute the sum of squared differences. Finally, np.sqrt() is applied to this sum.