TITLE: The distance from a point to a line segment
QUESTION [18 upvotes]: I'm pretty sure this may be a duplicate post somewhere, but I've searched all through the internet looking for a definite formula to calculate the distance between a point and a line segment. There are so many different variations of the formula that people have posted that its hard to determine which is correct.
I actually have several points that I will be looping through to get their distances. Each point will be within the boundary of the segment(if that makes any sense) so there will be no need to perform this theoretical check of the point being 'within' the segment that I've somewhat heard about. So can anyone please post the correct formula to calculate the distance  of a point C(x,y) from a line segment AB??

REPLY [25 votes]: Let the line segment be described by two points $s_1,s_2$, and you wish to find the nearest point on the segment to the point $p$.
We find the nearest point to the line through $s_1,s_2$, then 'project' back to the segment, then compute the distance.
A point on the line can be parameterized by $s(t) = s_1+t(s_2-s_1)$, note that $s(t)$ is on the line segment iff $t \in [0,1]$. The distance from $p$ to the point $s(t)$ given by the function $\phi(t)= \|s(t)-p\|$. It is easier to deal with $\phi^2$, which is a convex quadratic in $t$.
To find the minimizing '$t$', we set the derivative of $\phi^2$ to zero giving $\hat{t} = \frac{\langle p-s_1, s_2-s_1\rangle}{\|s_2-s_1\|^2}$. To find the $t$ that minimizes the distance on the segment, we 'project' back to $[0,1]$ using  $t^* = \min(\max(\hat{t},0),1)$. Then the minimum distance is given by $\|s(t^*)-p\|$.
Addendum:
Note that $\phi(t)^2 = \phi(\hat{t})^2+(t-\hat{t})^2 \|s_2-s_1\|^2$.
Hence the minimum distance will correspond to the value of $t \in [0,1]$ that results in the smallest $(t-\hat{t})^2$. It is straightforward to see that this is given by $t^*$ above.