在三维空间中有两个点
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.linalg.norm:
dist = numpy.linalg.norm(a-b)
这是因为欧氏距离是l2范数,而numpy.linalg.norm中ord参数的默认值是2。 要了解更多理论,请参阅数据挖掘介绍:
其他回答
我在matplotlib中找到了一个“dist”函数。mlab,但我认为它不够方便。
我把它贴在这里只是为了参考。
import numpy as np
import matplotlib as plt
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
# Distance between a and b
dis = plt.mlab.dist(a, b)
import math
dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)
使用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)))
可以像下面这样做。我不知道它有多快,但它没有使用NumPy。
from math import sqrt
a = (1, 2, 3) # Data point 1
b = (4, 5, 6) # Data point 2
print sqrt(sum( (a - b)**2 for a, b in zip(a, b)))
我喜欢np。点(点积):
a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
distance = (np.dot(a-b,a-b))**.5