Calculate Eucledian distance in python

Euclidean distance in Python

What is the Euclidean Distance?

Euclidean Distance is the line segment between two points in any dimension. Mathematically, we can evaluate it as the square root of the sum of squares of the difference between the given points.

Ways to Calculate the Euclidean distance in Python

Let us discuss how to calculate this value using different methods from different modules in Python.

Using the scipy.spatial.distance.euclidean() function

The scipy module can perform a variety of scientific calculations. The scipy.spatial.distance.euclidean() function is the most direct method to calculate the Euclidean distance and implements its formula internally for two points.

For example,

Output:

7.280109889280518

Using the math.dist() function

The math module has functions that can perform different mathematical calculations in Python. The math.dist() function calculates the Euclidean distance between two given points.

For example,

Output:

7.280109889280518

Using the numpy.sqrt(), numpy.square(), numpy.sum() functions

We can apply the discussed formula of calculating the Euclidean distance using these three functions.

We use methods from the numpy module when we have the coordinates stored in an array.

See the following code.

Output:

7.280109889280518

In the above example,

  • The numpy.square() function returns the square of the given array elements.
  • We calculate their sum using the numpy.sum() function.
  • The numpy.sqrt() function will calculate the square root of this value, that is essentially the Euclidean distance.

Using the numpy.linalg.norm() function

The numpy.linalg.norm() function calculates the vector norm of a given array. This value is essentially the same as the Euclidean distance.

See the code below.

Output:

7.280109889280518

Using the numpy.dot() function

We use the numpy.dot() function to calculate the dot product of two arrays.

We can use this function to implement the mathematical formula for the Euclidean distance.

For example,

Output:

7.280109889280518

In the above example,

  • We create an array that calculates the difference between the two points.
  • The numpy.dot() function calculates the dot product between this array and its transpose (calculated using .T).
  • The numpy.sqrt() function returns the square root of the final value.

Conclusion

We discussed different methods to calculate the Euclidean Distance using the math, numpy, and scipy modules. The numpy methods work on arrays and can be a little slow. The remaining two, scipy and math modules, execute faster. In these two modules, the points need not be in the form of an array.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *