w3resource

NumPy: Calculate the Euclidean distance

NumPy: Array Object Exercise-103 with Solution

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:

Previous: Write a NumPy program to convert a NumPy array into a csv file.
Next: Write a NumPy program to access last two columns of a multidimensional columns.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-103.php