What is the shortest distance from a point to a line segment? On determining this distance, two scenarios should be distinguished, as given in the picture below.

afstand tot lijnsegment

Assume that the line segment joins the points $$(x_1, y_1)$$ and $$(x_2, y_2)$$, and that we are searching for the shortest distance between this line segment and a point $$(x_3, y_3)$$. In the first scenario (left picture), the perpendicular line from the point $$(x_3, y_3)$$ intersects the straight line on which the line segment is situated in point $$(x_v, y_v)$$ on the line segment. This point is called the nadir. The shortest distance then equals the distance between the points $$(x_3, y_3)$$ and $$(x_v, y_v)$$. In the other scenario (right picture), the nadir is located outside the line segment, and the shortest distance is formed by the shortest distance from point $$(x_3, y_3)$$ to each end of the line segment $$(x_1, y_1)$$ and $$(x_2, y_2)$$.

Assignment

Example

>>> distance(152, 152, 285, 19)
188.09040379562165
>>> distance(100, 100, 195, 255)
181.79658962697843
>>> distance(200, 200, 195, 255)
55.226805085936306

>>> nadir(100, 100, 200, 200, 285, 19)
(152.0, 152.0)
>>> nadir(100, 100, 200, 200, 195, 255)
(None, None)

>>> shortest_distance(100, 100, 200, 200, 285, 19)
188.09040379562165
>>> shortest_distance(100, 100, 200, 200, 195, 255)
55.226805085936306