在三维空间中有两个点
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))
在三维空间中有两个点
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))
当前回答
首先求两个矩阵的差。然后,使用numpy的multiply命令应用元素乘法。然后,求元素与新矩阵相乘的和。最后,求求和的平方根。
def findEuclideanDistance(a, b):
euclidean_distance = a - b
euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
euclidean_distance = np.sqrt(euclidean_distance)
return euclidean_distance
其他回答
import math
dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)
使用numpy.linalg.norm:
dist = numpy.linalg.norm(a-b)
这是因为欧氏距离是l2范数,而numpy.linalg.norm中ord参数的默认值是2。 要了解更多理论,请参阅数据挖掘介绍:
用NumPy或一般的Python做这件事的最好方法是什么?我有:
最好的方法是最安全的,也是最快的
我建议使用低流量来获得可靠的结果,因为与编写自己的平方根计算器相比,下溢和溢出的几率非常小
我们来看看数学。函数,np。Hypot vs vanilla np.sqrt(np.sum(np.数组([i, j, k])) ** 2,轴=1))
i, j, k = 1e+200, 1e+200, 1e+200
math.hypot(i, j, k)
# 1.7320508075688773e+200
np.sqrt(np.sum((np.array([i, j, k])) ** 2))
# RuntimeWarning: overflow encountered in square
速度智慧的数学。Hypot看起来更好
%%timeit
math.hypot(i, j, k)
# 100 ns ± 1.05 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%%timeit
np.sqrt(np.sum((np.array([i, j, k])) ** 2))
# 6.41 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
下溢
i, j = 1e-200, 1e-200
np.sqrt(i**2+j**2)
# 0.0
溢出
i, j = 1e+200, 1e+200
np.sqrt(i**2+j**2)
# inf
没有下溢
i, j = 1e-200, 1e-200
np.hypot(i, j)
# 1.414213562373095e-200
没有溢出
i, j = 1e+200, 1e+200
np.hypot(i, j)
# 1.414213562373095e+200
请参考
从Python 3.8开始,math模块直接提供dist函数,它返回两点之间的欧几里得距离(以元组或坐标列表的形式给出):
from math import dist
dist((1, 2, 6), (-2, 3, 2)) # 5.0990195135927845
如果你使用列表:
dist([1, 2, 6], [-2, 3, 2]) # 5.0990195135927845
这个公式很容易用
distance = np.sqrt(np.sum(np.square(a-b)))
它实际上只是使用毕达哥拉斯定理来计算距离,通过将Δx, Δy和Δz的平方相加,并对结果进行根运算。