【问题标题】:How do I find the distance between two points? [closed]如何找到两点之间的距离? [关闭]
【发布时间】:2011-07-10 20:19:21
【问题描述】:

假设我有 x1, y1 和 x2, y2。

我怎样才能找到它们之间的距离? 这是一个简单的数学函数,但是网上有这个的sn-p吗?

【问题讨论】:

  • @Greg:他的记录说不。 @TIMEX:搜索不起作用?说真的:google.com/search?q=python+distance+points
  • -1 表示“网上有这个的 sn-p 吗?”说真的,@TIMEX,如果在网上搜索代码 sn-p 太难了,那么现在是改变职业的时候了。
  • 我很惊讶这个问题已经结束。它出现在我对“python pythagoras”的搜索结果中,也是我发现 math.hypot 存在的方式。
  • 好吧,我只是想在google的第一页添加一个注释,这个。看到“只是谷歌它”作为第一个答案总是让我感到沮丧。很明显,这个问题有一些需要。
  • @GlennMaynard 我是通过搜索“python 距离点”来的,现在该怎么办?

标签: python math


【解决方案1】:
dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

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

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

【讨论】:

  • 这不是python中的“权力”吗?不是**吗?
  • @TIMEX:是的。这一变化现在反映在@MitchWheat 的帖子中
  • @RobFisher - 显式编写此表达式实际上可能比调用 math.hypot更快,因为它用内联字节码替换了函数调用。
【解决方案2】:

我们不要忘记 math.hypot:

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

这是作为 sn-p 的一部分的假设,用于计算由 (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)

【讨论】:

  • Python3 不再允许元组作为 lambda 参数,因此函数变为: ptdiff = lambda p: (p[0][0]-p[1][0], p[0][1 ]-p[1][1]) diffs = map (ptdiff, zip(pts[:-1],pts[1:])) path = sum(math.hypot(d1,d2) for d1,d2 in diffs )
【解决方案3】:

它是勾股定理的实现。链接:http://en.wikipedia.org/wiki/Pythagorean_theorem

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2019-09-16
    • 2013-10-09
    • 1970-01-01
    • 2016-09-13
    相关资源
    最近更新 更多