Skip to content

Instantly share code, notes, and snippets.

@andriitishchenko
Created February 12, 2023 12:29
Show Gist options
  • Save andriitishchenko/c090be979e3ff39a26463e9cc2f5a238 to your computer and use it in GitHub Desktop.
Save andriitishchenko/c090be979e3ff39a26463e9cc2f5a238 to your computer and use it in GitHub Desktop.
The location of the point on the line from the beginning at the specified distance
import math
"""
A(1,0) C(?) B(5,5)
*-------------*---------*
AC=5
"""
import math
def find_point(a, b, distance):
dx = b[0] - a[0]
dy = b[1] - a[1]
dis = math.sqrt(dx**2 + dy**2)
k = distance / dis
c = (a[0] + dx * k, a[1] + dy * k)
return c
"""
This function can be used like this:
"""
a = (1, 0)
b = (5, 5)
distance = 5
c = find_point(a, b, distance)
print(c)
"""
In this version, math.hypot is used instead of math.sqrt(dx**2 + dy**2)
to calculate the distance between the two points a and b.
math.hypot is a more efficient and concise way to calculate the Euclidean distance between two points.
"""
def find_point(a, b, distance):
dx, dy = b[0] - a[0], b[1] - a[1]
dis = math.hypot(dx, dy)
k = distance / dis
return (a[0] + dx * k, a[1] + dy * k)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment