Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the Euclidean distance be calculated with NumPy?

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)) 
like image 421
Nathan Fellman Avatar asked Sep 09 '09 19:09

Nathan Fellman


People also ask

How does Python calculate Euclidean distance?

dist() method returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point. Note: The two points (p and q) must be of the same dimensions.

How do you calculate Euclidean distance?

The Euclidean distance formula is used to find the distance between two points on a plane. This formula says the distance between two points (x1 1 , y1 1 ) and (x2 2 , y2 2 ) is d = √[(x2 – x1)2 + (y2 – y1)2].


1 Answers

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

like image 85
u0b34a0f6ae Avatar answered Sep 20 '22 23:09

u0b34a0f6ae