在三维空间中有两个点

a = (ax, ay, az)
b = (bx, by, bz)

我想计算它们之间的距离:

dist = sqrt((ax-bx)^2 + (ay-by)^2 + (az-bz)^2)

我如何用NumPy做到这一点?我有:

import numpy
a = numpy.array((ax, ay, az))
b = numpy.array((bx, by, bz))

当前回答

计算多维空间的欧氏距离:

 import math

 x = [1, 2, 6] 
 y = [-2, 3, 2]

 dist = math.sqrt(sum([(xi-yi)**2 for xi,yi in zip(x, y)]))
 5.0990195135927845

其他回答

import numpy as np
from scipy.spatial import distance
input_arr = np.array([[0,3,0],[2,0,0],[0,1,3],[0,1,2],[-1,0,1],[1,1,1]]) 
test_case = np.array([0,0,0])
dst=[]
for i in range(0,6):
    temp = distance.euclidean(test_case,input_arr[i])
    dst.append(temp)
print(dst)

一个很好的句子:

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

但是,如果速度是一个问题,我建议在您的机器上进行试验。我发现,在我的机器上,使用数学库的√rt和**运算符对平方进行运算要比使用一行NumPy解决方案快得多。

我用这个简单的程序进行了测试:

#!/usr/bin/python
import math
import numpy
from random import uniform

def fastest_calc_dist(p1,p2):
    return math.sqrt((p2[0] - p1[0]) ** 2 +
                     (p2[1] - p1[1]) ** 2 +
                     (p2[2] - p1[2]) ** 2)

def math_calc_dist(p1,p2):
    return math.sqrt(math.pow((p2[0] - p1[0]), 2) +
                     math.pow((p2[1] - p1[1]), 2) +
                     math.pow((p2[2] - p1[2]), 2))

def numpy_calc_dist(p1,p2):
    return numpy.linalg.norm(numpy.array(p1)-numpy.array(p2))

TOTAL_LOCATIONS = 1000

p1 = dict()
p2 = dict()
for i in range(0, TOTAL_LOCATIONS):
    p1[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
    p2[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))

total_dist = 0
for i in range(0, TOTAL_LOCATIONS):
    for j in range(0, TOTAL_LOCATIONS):
        dist = fastest_calc_dist(p1[i], p2[j]) #change this line for testing
        total_dist += dist

print total_dist

在我的机器上,math_calc_dist运行得比numpy_calc_dist快得多:1.5秒对23.5秒。

为了在fastst_calc_dist和math_calc_dist之间获得一个可测量的差异,我必须将TOTAL_LOCATIONS增加到6000。然后,fastst_calc_dist耗时约50秒,math_calc_dist耗时约60秒。

您也可以尝试使用numpy。SQRT和numpy。不过这两个运算都比我机器上的数学运算要慢。

我的测试使用Python 2.6.6运行。

对于大量的距离,我能想到的最快的解决方案是使用numexpr。在我的机器上,它比使用numpy einsum更快:

import numexpr as ne
import numpy as np
np.sqrt(ne.evaluate("sum((a_min_b)**2,axis=1)"))
import numpy as np
# any two python array as two points
a = [0, 0]
b = [3, 4]

首先将list更改为numpy数组,并像这样做:print(np.linalg.norm(np.array(a) - np.array(b)))。第二种方法直接从python列表as: print(np.linalg.norm(np.subtract(a,b)))

使用Python 3.8,这非常简单。

https://docs.python.org/3/library/math.html#math.dist

math.dist(p, q)

返回给定两点p和q之间的欧氏距离 作为坐标序列(或可迭代对象)。这两点一定有 相同的维度。 大致相当于: √(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))