Calculate Euclidean Distance in Python In math, the Euclidean distance is the shortest distance between two points in a dimensional space.

To calculate the Euclidean distance in Python, use either the NumPy or SciPy, or math package. In this tutorial, we will learn how to use all of those packages to achieve the final result.

Use the distance.euclidean() Function to Find the Euclidean Distance Between Two Points

The SciPy package is used for technical and scientific computing in Python. The distance module within SciPy contains the distance.euclidean() function, which returns the Euclidean distance between two points.

To use it, import distance from scipy.spatial and pass your two tuples of coordinates as the first and second arguments of distance.euclidean().

from scipy.spatial import distance

x = (3, 6, 8)
y = (11, 12, 16)

print(distance.euclidean(x, y))
12.806248474865697

If you need to install SciPy, install it VIA pip with the following terminal command:

pip install scipy

Get Euclidean Distance Between Two Point with math.dist() Function

If you are already using the Python math package and would rather not import SciPy, use the math.dist() function instead. Pass the coordinates as the first and second arguments of math.dist() to get the Euclidean distance.

import math

x = (3, 6, 8)
y = (11, 12, 16)

print(math.dist(x, y))
12.806248474865697

Find Euclidean Distance from Coordinates with NumPy

It is also possible to get the Euclidean distance using the NumPy package. The two disadvantages of using NumPy for solving the Euclidean distance over other packages is you have to convert the coordinates to NumPy arrays and it is slower.

import numpy as np
x = np.array((3, 6, 8))
y = np.array((11, 12, 16))

dist = np.linalg.norm(x-y)

print(dist)
12.806248474865697

Related Tutorials How to Calculate Mean, Median, Mode and Range in Python

October 07, 2020 How to Calculate Exponent in Python

May 28, 2021 How to Calculate a Square Root in Python

May 12, 2021 Truncate Float in Python

June 29, 2021 How to Calculate a Percentage in Python

April 21, 2021 Cosine of Degree Values in NumPy

September 17, 2021