Point-to-Segment Proximity

In many problems, we need to determine the distance between a point $\mathbf {p}$ and a polyline consisting of multiple segments. The computational cost of this problem grows linearly with the number of points defining the polyline, so comparing the point with each individual segment must be very fast.

This section defines a segment as the portion of a line bounded by the points $\mathbf{a}$ and $\mathbf{b}$. The point $\mathbf {p}$ and the segment can have one of three relationships: the nearest point is $\mathbf{a}$, the nearest point is $\mathbf{b}$, or the nearest point lies between the two endpoints. From a purely computational perspective, calculating these three distances would require nine multiplications, six additions, one division, and three comparisons. This section shows how the dot product can be used to make the comparison more computationally efficient.

Without loss of generality, assume that $\mathbf{a}=(0,0)^{\top}$. From the definition of the dot product

\begin{displaymath}
\mathbf{p} \cdot \mathbf{b} = \cos \alpha \Vert \mathbf{p} \Vert \Vert \mathbf{b} \Vert
\end{displaymath} (1.70)

and the length of the orthogonal projection of $\mathbf {p}$ onto $\mathbf{b}$
\begin{displaymath}
\cos \alpha \Vert \mathbf{p} \Vert = \frac { \mathbf{p} \cdot \mathbf{b} } { \Vert \mathbf{b} \Vert }
\end{displaymath} (1.71)

we can calculate the point-to-segment distance more efficiently. The nearest point to $\mathbf {p}$ is $\mathbf{a}$ if and only if $\alpha > \pi/2$, that is, $\mathbf{p} \cdot \mathbf{b} <0$; the nearest point is $\mathbf{b}$ if and only if the projection of $\mathbf {p}$ onto $\mathbf{b}$ is greater than $\Vert\mathbf{b}\Vert$, that is, $\mathbf{p} \cdot \mathbf{b} > \Vert \mathbf{b} \Vert^2$. In this case, only four multiplications and two additions are needed to determine proximity. Only if the nearest point lies in the interior do we need to proceed with the conventional point-to-line distance calculation.

Paolo medici
2026-10-19