Let's say I have x1, y1 and also x2, y2.
假设我有x1,y1以及x2,y2。
How can I find the distance between them? It's a simple math function, but is there a snippet of this online?
我怎样才能找到它们之间的距离?这是一个简单的数学函数,但是有一个在线的片段吗?
3 个解决方案
#1
61
dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
As others have pointed out, you can also use the equivalent built-in math.hypot()
:
正如其他人指出的那样,你也可以使用等效的内置math.hypot():
dist = math.hypot(x2 - x1, y2 - y1)
#2
54
Let's not forget math.hypot:
我们不要忘记math.hypot:
dist = math.hypot(x2-x1, y2-y1)
Here's hypot as part of a snippet to compute the length of a path defined by a list of x,y tuples:
这是作为计算由x,y元组列表定义的路径长度的片段的一部分的hypot:
from math import hypot
pts = [
(10,10),
(10,11),
(20,11),
(20,10),
(10,10),
]
ptdiff = lambda (p1,p2): (p1[0]-p2[0], p1[1]-p2[1])
diffs = map(ptdiff, zip(pts,pts[1:]))
path = sum(hypot(*d) for d in diffs)
print path
#3
14
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
它是毕达哥拉斯定理的一个实现。链接:http://en.wikipedia.org/wiki/Pythagorean_theorem
#1
61
dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
As others have pointed out, you can also use the equivalent built-in math.hypot()
:
正如其他人指出的那样,你也可以使用等效的内置math.hypot():
dist = math.hypot(x2 - x1, y2 - y1)
#2
54
Let's not forget math.hypot:
我们不要忘记math.hypot:
dist = math.hypot(x2-x1, y2-y1)
Here's hypot as part of a snippet to compute the length of a path defined by a list of x,y tuples:
这是作为计算由x,y元组列表定义的路径长度的片段的一部分的hypot:
from math import hypot
pts = [
(10,10),
(10,11),
(20,11),
(20,10),
(10,10),
]
ptdiff = lambda (p1,p2): (p1[0]-p2[0], p1[1]-p2[1])
diffs = map(ptdiff, zip(pts,pts[1:]))
path = sum(hypot(*d) for d in diffs)
print path
#3
14
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
它是毕达哥拉斯定理的一个实现。链接:http://en.wikipedia.org/wiki/Pythagorean_theorem