Skip to content

Instantly share code, notes, and snippets.

@AndreLester
Created June 15, 2026 10:22
Show Gist options
  • Select an option

  • Save AndreLester/cc91b25fbfd7839223ebbe4d9fd66540 to your computer and use it in GitHub Desktop.

Select an option

Save AndreLester/cc91b25fbfd7839223ebbe4d9fd66540 to your computer and use it in GitHub Desktop.
Calculate the euclidian distance between an array of points to a line segment
def lineseg_dists(p, a, b):
# Handle case where p is a single point, i.e. 1d array.
p = np.atleast_2d(p)
# TODO for you: consider implementing @Eskapp's suggestions
if np.all(a == b):
return np.linalg.norm(p - a, axis=1)
# normalized tangent vector
d = np.divide(b - a, np.linalg.norm(b - a))
# signed parallel distance components
s = np.dot(a - p, d)
t = np.dot(p - b, d)
# clamped parallel distance
x = np.maximum.reduce([s, t, np.zeros(len(p))])
# perpendicular distance component
# switch to dot-prod method which is dimension-agnostic
y = np.linalg.norm(p - b - t * d)
# use hypot() to improve accuracy
return np.hypot(x, y)
@AndreLester

Copy link
Copy Markdown
Author

Copied from Stackoverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment