views:

1169

answers:

2

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:

a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
+3  A: 

Another instance of this problem solving method. As soon as I submitted the question I got it:

def dist(x,y):   
    return numpy.sqrt(numpy.sum((x-y)**2))

a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
dist_a_b = dist(a,b)
Nathan Fellman
can you use numpy's sqrt and/or sum implementations? That should make it faster (?).
kaizer.se
Thanks! I'll update the answer
Nathan Fellman
I found this on the other side of the interwebs `norm = lambda x: N.sqrt(N.square(x).sum())` ; `norm(x-y)`
kaizer.se
scratch that. it had to be somewhere. here it is: `numpy.linalg.norm(x-y)`
kaizer.se
+6  A: 

Use

dist = numpy.linalg.norm(a-b)
kaizer.se
You beat me to it :)
Mark Lavin
I knew there was a reason for me not to accept my own answer :-). Just for the record, I managed to see Mark Lavin's answer before he deleted it. I liked it better for the link to Python's docs and the explanation. Can you add some details?
Nathan Fellman
The linalg.norm docs can be found here:http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.htmlMy only real comment was sort of pointing out the connection between a norm (in this case the Frobenius norm/2-norm which is the default for norm function) and a metric (in this case Euclidean distance).
Mark Lavin