Closest points on two line segments (source code)

= Closest points on two line segments

For <line segments> $P+sd$ and $Q+te$, $0\leq s,t\leq1$, the squared <Euclidean distance> is a <convex quadratic function> on a square. Its minimum is either an admissible stationary point or a minimum on one of the four edges. Each edge minimum is a point-to-segment <orthogonal projection>, restricted to the interval. Testing these five candidates gives a complete algorithm; when the directions are parallel, the edge candidates suffice. Independently restricting both coordinates of the unconstrained stationary point is generally incorrect because the variables are coupled by $d\cdot e$.