snippetpythonCriticalCanonical
How can the Euclidean distance be calculated with NumPy?
Viewed 0 times
euclideanwithhownumpycalculatedthedistancecan
Problem
I have two points in 3D space:
I want to calculate the distance between them:
How do I do this with NumPy? I have:
a = (ax, ay, az)
b = (bx, by, bz)
I want to calculate the distance between them:
dist = sqrt((ax-bx)^2 + (ay-by)^2 + (az-bz)^2)
How do I do this with NumPy? I have:
import numpy
a = numpy.array((ax, ay, az))
b = numpy.array((bx, by, bz))
Solution
Use
This works because the Euclidean distance is the l2 norm, and the default value of the
For more theory, see Introduction to Data Mining:
numpy.linalg.norm:dist = numpy.linalg.norm(a-b)This works because the Euclidean distance is the l2 norm, and the default value of the
ord parameter in numpy.linalg.norm is 2.For more theory, see Introduction to Data Mining:
Code Snippets
dist = numpy.linalg.norm(a-b)Context
Stack Overflow Q#1401712, score: 1354
Revisions (0)
No revisions yet.