在三维空间中有两个点

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和b,你可以用also:

distance = np.sqrt(np.sum((a-b)**2))

其他回答

import math

dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)

使用scipy.spatial.distance.euclidean:

from scipy.spatial import distance
a = (1, 2, 3)
b = (4, 5, 6)
dst = distance.euclidean(a, b)

我在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)

这个公式很容易用

distance = np.sqrt(np.sum(np.square(a-b)))

它实际上只是使用毕达哥拉斯定理来计算距离,通过将Δx, Δy和Δz的平方相加,并对结果进行根运算。

从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