Categories
Python Answers

How to calculate the Euclidean distance with Python NumPy?

Spread the love

Sometimes, we want to calculate the Euclidean distance with Python NumPy.

In this article, we’ll look at how to calculate the Euclidean distance with Python NumPy.

How to calculate the Euclidean distance with Python NumPy?

To calculate the Euclidean distance with Python NumPy, we can use the numpy.linalg.norm method.

For instance, we write:

import numpy

a = numpy.array((1, 2, 3))
b = numpy.array((4, 5, 6))

dist = numpy.linalg.norm(a - b)
print(dist)

We create 3 NumPy arrays a and b.

Then we call numpy.linalg.norm with a - b to calculate the distance between points a and b.

Therefore, dist is 5.196152422706632.

Conclusion

To calculate the Euclidean distance with Python NumPy, we can use the numpy.linalg.norm method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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