How do I find the distance between two points? [closed]

Posted on

Question :

How do I find the distance between two points? [closed]

Let’s say I have x1, y1 and also x2, y2.

How can I find the distance between them?
It’s a simple math function, but is there a snippet of this online?

Asked By: TIMEX


Answer #1:

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)
Answered By: Mitch Wheat

Answer #2:

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 = [

# 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)
Answered By: PaulMcG

Answer #3:

enter image description here
It is an implementation of Pythagorean theorem. Link:

Answered By: Maciej Ziarko

Leave a Reply

Your email address will not be published. Required fields are marked *