Calculate the Euclidean distance using NumPy
Last Updated :
05 Jul, 2021
In simple terms, 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.
Method #1: Using linalg.norm()
Python3
import numpy as np
point1 = np.array(( 1 , 2 , 3 ))
point2 = np.array(( 1 , 1 , 1 ))
dist = np.linalg.norm(point1 - point2)
print (dist)
|
Output:
2.23606797749979
Method #2: Using dot()
Python3
import numpy as np
point1 = np.array(( 1 , 2 , 3 ))
point2 = np.array(( 1 , 1 , 1 ))
temp = point1 - point2
sum_sq = np.dot(temp.T, temp)
print (np.sqrt(sum_sq))
|
Output:
2.23606797749979
Method #3: Using square() and sum()
Python3
import numpy as np
point1 = np.array(( 1 , 2 , 3 ))
point2 = np.array(( 1 , 1 , 1 ))
sum_sq = np. sum (np.square(point1 - point2))
print (np.sqrt(sum_sq))
|
Output:
2.23606797749979
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...