How can the Euclidean distance be calculated with NumPy?

Nathan Fellman picture Nathan Fellman · Sep 9, 2009 · Viewed 871.5k times · Source

I have two points in 3D:

(xa, ya, za)
(xb, yb, zb)

And I want to calculate the distance:

dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)

What's the best way to do this with NumPy, or with Python in general? I have:

import numpy
a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))

Answer

u0b34a0f6ae picture u0b34a0f6ae · Sep 9, 2009

Use numpy.linalg.norm:

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

You can find the theory behind this in Introduction to Data Mining

This works because the Euclidean distance is the l2 norm, and the default value of the ord parameter in numpy.linalg.norm is 2.

enter image description here