# Determing the distance from a line segment to a point in 3-space

Imagine I have a line segment defined by endpoints $p_1$ and $p_2$, and some 3-space coordinate $q$.

Is there a robust (in the sense of never giving divide-by-zero errors) way to quickly determine the distance between the point and line segment?

Update – The neat answer provided by julien seems to provide the distance to a line, not a line segment as specified in the problem description.

#### Solutions Collecting From Web of "Determing the distance from a line segment to a point in 3-space"

1) I will first show how to compute the distance between $p$ and the line $(p_1,p_2)$.

Let $u$ be the vector $\vec{p_1p_2}$ and let $v$ be the vector $\vec{p_1q}$.

You want to find the orthogonal projection $p$ of $q$ on the line.

This is given by the formula
$$p=p_1+\frac{(u,v)}{\|u\|^2}u.$$

Once you have $p$, you distance is simply the distance between $q$ and $p$, namely
$$d(q,p)=\|\vec{qp}\|.$$

Note: $(u,v)$ denotes the Euclidean inner-product and $\|u\|=\sqrt{(u,u)}$ the Euclidean norm.

2) Now let us consider the distance to the segment $[p_1,p_2]$. Recall that $p$ is the orthogonal projection of $q$ on the line.
There are three cases:

a) The projection $p$ belongs to $[p_1,p_2]$, then your distance is $d(q,p)=\|\vec{qp}\|$.

b) The projection $p$ belongs to $(-\infty,p_1)$, the infinite portion of the line which starts at $p_1$ excluded and does not contain $p_2$. Then your distance is $d(q,p_1)=\|\vec{qp_1}\|$.

c) The projection $p$ belongs to $(p_2,+\infty)$, the infinite portion of the line which starts at $p_2$ excluded and does not contain $p_1$. In this case, it is $d(q,p_2)=\|\vec{qp_2}\|$.

3) How to make this an algorithm.

3.1) Compute
$$\frac{(u,v)}{\|u\|^2}.$$

3.2) If this is in $[0,1]$, you are in case a), so compute $p$ and return $d(q,p)=\|\vec{qp}\|$.

3.3)If this is negative, you are in case b), so return $d(q,p_1)=\|\vec{qp_1}\|$.

3.4) If this is greater than $1$, you are in case c), so the answer is $d(q,p_2)=\|\vec{qp_2}\|$.

I believe this is robust, since this never leads to a division by $0$.

Well for a segment you have to consider three situations. If the solution p is in the segment then it is the projection. Otherwise the closest point is either p_1 or p_2 depending on which is closer to p.