如何计算两点之间的距离?

92 投票
3 回答
213921 浏览
提问于 2025-04-16 13:13

假设我有两个点,分别是 x1, y1 和 x2, y2。

我该怎么计算这两个点之间的距离呢?这其实是一个简单的数学公式,但网上有没有相关的代码片段可以参考呢?

3 个回答

18

在这里输入图片描述 这是一个关于勾股定理的实现。链接:http://en.wikipedia.org/wiki/Pythagorean_theorem

72

别忘了 math.hypot 这个函数:

dist = math.hypot(x2-x1, y2-y1)

下面是一个使用 hypot 函数的代码片段,它可以用来计算由一系列 (x, y) 坐标点定义的路径的长度:

from math import hypot

pts = [
    (10,10),
    (10,11),
    (20,11),
    (20,10),
    (10,10),
    ]

# Py2 syntax - no longer allowed in Py3
# ptdiff = lambda (p1,p2): (p1[0]-p2[0], p1[1]-p2[1])
ptdiff = lambda p1, p2: (p1[0]-p2[0], p1[1]-p2[1])

diffs = (ptdiff(p1, p2) for p1, p2 in zip (pts, pts[1:]))
path = sum(hypot(*d) for d in  diffs)
print(path)
150
dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
dist = math.hypot(x2 - x1, y2 - y1)

正如其他人提到的,你也可以使用内置的 math.hypot() 函数,它的功能是一样的:

撰写回答