如何找到两点之间的距离?

TIM*_*MEX 48 python math

假设我有x1,y1以及x2,y2.

我怎样才能找到它们之间的距离?这是一个简单的数学函数,但是有一个在线的片段吗?

Mit*_*eat 83

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
Run Code Online (Sandbox Code Playgroud)

正如其他人指出的那样,您也可以使用等效的内置math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)
Run Code Online (Sandbox Code Playgroud)

  • @RobFisher - 显式写这个表达式实际上可能比调用`math.hypot`快**因为它用内联字节码替换了一个函数调用. (6认同)
  • 你的意思是http://en.wikipedia.org/wiki/Euclidean_distance? (2认同)

Pau*_*McG 61

我们不要忘记math.hypot:

dist = math.hypot(x2-x1, y2-y1)
Run Code Online (Sandbox Code Playgroud)

这是作为计算由x,y元组列表定义的路径长度的片段的一部分的hypot:

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)
Run Code Online (Sandbox Code Playgroud)


Mac*_*rko 18

在此输入图像描述 它是毕达哥拉斯定理的一个实现.链接:http://en.wikipedia.org/wiki/Pythagorean_theorem