cppAcademy
← Learning PathLESSON 5 / 25 · COMPUTATIONAL GEOMETRY · 30 MIN✕

Distance Between Points, Lines, and Segments

Distance depends on the object: the closest point on an infinite line may lie outside a segment. Projection unifies the calculations and makes degenerate cases explicit. This program prints the distance from P to A, to the supporting line AB and to the segment AB. These primitives are useful for clearance, collision checks and nearest-boundary problems.

Prerequisites: Dot Product, Cross Product and Orientation.

Build the idea

  1. Separate the three questions

    Point distance is |P−A|. A line allows any parameter t in A+t(B−A); a segment restricts t to [0,1]. For A=(0,0),B=(4,0),P=(6,3), the line distance is 3 but the segment distance is √13 because its nearest legal point is B. Drawing those three coordinates immediately shows why the answers differ.

  2. Find the projection parameter

    Let v=B−A and w=P−A. Minimizing |w−tv|² gives t=(w·v)/(v·v), the same orthogonality condition as the dot-product lesson. If t<0 the minimum on [0,1] is A; if t>1 it is B; otherwise the projected point is on the segment. Clamping exactly implements these cases.

    closest=A+clamp((P−A)·v/(v·v),0,1)·v

  3. Compute the line distance

    The magnitude |cross(v,w)| is parallelogram area. It is also base length |v| times perpendicular height, so divide by |v|. This formula avoids constructing the foot solely for the line distance. It remains valid for vertical lines; no slope or y-intercept case distinction is needed.

  4. Handle a collapsed segment

    If A=B, v·v=0. The segment is a point and its distance is |P−A|; an infinite line is not defined by these identical endpoints. The program prints UNDEFINED LINE for the middle result and the correct point distance for the segment result. It checks this condition before either division.

    Projection beyond a segment: P projects to the line at H, while B is the nearest point on the segment.ABPH
  5. Trace the implementation

    The Point operators support v,w and projected points. length2 stores v·v, t stores the clamped parameter, and difference stores P minus its closest segment point. hypotl evaluates lengths. Inputs are finite moderate values; testing length2==0 recognizes exactly identical represented endpoints, not every very short segment. Nearly collapsed floating geometry can still be ill-conditioned and needs task-specific scaling.

C++17 implementation

This is a complete program. Compile with C++17 and enter the input described below.

#include<iostream>
#include<cmath>
#include<algorithm>
#include<iomanip>
struct Point{
    long double x,y;
    Point operator-(Point b)const{
        return {x-b.x,y-b.y};
    }
    Point operator+(Point b)const{
        return {x+b.x,y+b.y};
    }
    Point operator*(long double t)const{
        return {x*t,y*t};
    }
};
long double dot(Point a,Point b){
    return a.x*b.x+a.y*b.y;
}
int main(){
    Point a,b,p;
    std::cin>>a.x>>a.y>>b.x>>b.y>>p.x>>p.y;
    Point v=b-a,w=p-a;
    long double length2=dot(v,v);
    std::cout<<std::fixed<<std::setprecision(6)<<std::hypotl(w.x,w.y)<<'\n';
    if(length2==0){
        std::cout<<"UNDEFINED LINE\n"<<std::hypotl(w.x,w.y)<<'\n';
        return 0;
    }
    std::cout<<std::fabs(v.x*w.y-v.y*w.x)/std::sqrt(length2)<<'\n';
    long double t=std::clamp(dot(w,v)/length2,0.0L,1.0L);
    Point difference=p-(a+v*t); // Clamping restricts the projection to the segment.
    std::cout<<std::hypotl(difference.x,difference.y)<<'\n';
}

Complexity analysis

O(1) time and auxiliary space. Each distance uses a constant number of vector operations. Comparing squared integer point distances elsewhere avoids unnecessary square roots.

Common mistakes and edge cases. Never divide by the squared length of a collapsed segment. Clamp the projection for a segment, not for an infinite line. Use floating division for t. Avoid a universal epsilon that turns distinct short segments into points without a scale argument.

Example input and output

Read ax ay bx by px py as finite numbers within ±10^6. Print distance P–A, line distance or UNDEFINED LINE, then segment distance, to six decimals.

Input

0 0 4 0 6 3

Output

6.708204
3.000000
3.605551

The projection parameter is 24/16=1.5 and clamps to 1, so the closest segment point is (4,0).

Practical applications

Use for nearest obstacles, checking whether a point is within a radius of a segment, and measuring distance to polygon edges. Polygon distance scans all edges; spatial indices can accelerate many large queries.

Check your understanding

What happens when the projection parameter exceeds 1?

Put it into practice

Test P over the midpoint, beyond A, and with A=B.

Show a hint

The line and segment answers agree only when the perpendicular foot is allowed.

Further reading