Skip to content

Instantly share code, notes, and snippets.

@HYChou0515
Created February 5, 2023 04:46
Show Gist options
  • Save HYChou0515/c763fc442acdf54ac48ff5736c00db74 to your computer and use it in GitHub Desktop.
Save HYChou0515/c763fc442acdf54ac48ff5736c00db74 to your computer and use it in GitHub Desktop.
Orthogonal projection of a point onto a line
def vec_scale(v: tuple[float, float], a: float):
return (a * v[0], a * v[1])
def vec_mul_add(v1: tuple[float, float], v2: tuple[float, float], a: float = 1):
"""calc v1+a*v2"""
return (v1[0] + a * v2[0], v1[1] + a * v2[1])
def inner_prod(v1: tuple[float, float], v2: tuple[float, float]):
"""v1^T * v2"""
return v1[0] * v2[0] + v1[1] * v2[1]
def solve(coef: tuple[float, float, float], p: tuple[float, float]):
"""
Params:
coef: 3-tuple (a,b,c) to represent the linear equation ax+by+c=0.
p: 2-tuple (px,py) to represent the point.
"""
a, b, c = coef
# find p0 at the line
if b == 0:
p0 = (-c / a, 0)
else:
p0 = (0, -c / b)
# find v
if a == 0:
v = (1, 0)
elif b == 0:
v = (0, 1)
else:
v = (b, -a)
return vec_mul_add(
p0, vec_scale(v, inner_prod(vec_mul_add(p, p0, -1), v) / inner_prod(v, v))
)
print(solve((-5, 3, 15), (-4, 5)))
# output: (3.3529411764705883, 0.5882352941176467)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment