假设我有 x1,y1,还有 x2,y2。
我怎样才能找到他们之间的距离? 这是一个简单的数学函数,但是网上有这个函数的片段吗?
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)
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
Let's not forget 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:
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)