NumPy: Calculate the Euclidean distance
Calculate Euclidean Distance
Write a NumPy program to calculate the Euclidean distance.
From Wikipedia: In mathematics, the Euclidean distance or Euclidean metric is the "ordinary" straight-line distance between two points in Euclidean space. With this distance, Euclidean space becomes a metric space. The associated norm is called the Euclidean norm. Older literature refers to the metric as the Pythagorean metric
Sample Solution:
Python Code:
# Importing the 'distance' module from 'scipy.spatial'
from scipy.spatial import distance
# Defining the coordinates for point p1 and point p2 in three dimensions
p1 = (1, 2, 3)
p2 = (4, 5, 6)
# Calculating the Euclidean distance between points p1 and p2 using 'distance.euclidean()'
d = distance.euclidean(p1, p2)
# Printing the calculated Euclidean distance between the two points
print("Euclidean distance: ", d)
Sample Output:
Euclidean distance: 5.196152422706632
Explanation:
In the above code –
- from scipy.spatial import distance: Import the distance module from the scipy.spatial package.
- p1 = (1, 2, 3): Define point p1 with coordinates (1, 2, 3).
- p2 = (4, 5, 6): Define point p2 with coordinates (4, 5, 6).
- d = distance.euclidean(p1, p2): Calculate the Euclidean distance between point p1 and point p2 using the euclidean() function from the distance module. The Euclidean distance is the straight-line distance between two points in a space.
- Finally print() function prints the calculated Euclidean distance.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics