Function Repository Resource:

PointLineDistance

Source Notebook

Get the distance and normal line between a point and line

Contributed by: Ed Pegg Jr

ResourceFunction["PointLineDistance"][p,{a,b}]

returns the distance between the point p and the infinite line through points a and b, as well as the coordinates realizing that distance.

ResourceFunction["PointLineDistance"][Point[p],Line[{a,b}]]

returns the distance between point p and the infinite line through points a and b, as well as the Line realizing that distance.

Examples

Basic Examples (2) 

Calculate distance and normal line for (1,1) and the x-axis:

In[1]:=
p = Point[{1, 1}];
l = Line[{{0, 0}, {2, 0}}];
pld = ResourceFunction["PointLineDistance"][p, l]
Out[3]=

Show the construction:

In[4]:=
Graphics[{p, l, Green, pld[[2]]}]
Out[5]=

For just the distance, RegionDistance can be used:

In[6]:=
RegionDistance[l, {1, 1}]
Out[6]=

For the point on the line, RegionNearest can be used:

In[7]:=
RegionNearest[l, {1, 1}]
Out[7]=

For a more arbitrary point, the line is assumed to be infinite:

In[8]:=
p = Point[{x, 1}];
l = Line[{{0, 0}, {2, 0}}];
pld = ResourceFunction["PointLineDistance"][p, l]
Out[10]=

With RegionNearest, InfiniteLine must be specified:

In[11]:=
l = InfiniteLine[{{0, 0}, {2, 0}}];
RegionNearest[l, {x, 1}]
Out[12]=

Scope (2) 

Using Point and Line is optional:

In[13]:=
p = {0, 0};
l = {{0, 3}, {2, 4}};
pld = ResourceFunction["PointLineDistance"][p, l]
Out[15]=

Use PointLineDistance on a point and line in 3D:

In[16]:=
p = {0, 0, 0};
l = {{0, 3, -1}, {2, 4, 2}};
pld = ResourceFunction["PointLineDistance"][p, l]
Out[17]=

Applications (2) 

Plot a tilted cylinder:

In[18]:=
ContourPlot3D[
 First[ResourceFunction[
     "PointLineDistance"][{x, y, z}, {{0, 0, 0}, {1, 1, 1}}]] == 3/4 //
   Evaluate, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}]
Out[18]=

A parabola can be defined as the locus of points that are equidistant between a given point (the focus) and a given line (the directrix). Plot a parabola, given a focus and directrix:

In[19]:=
With[{point = {0, 1}, line = {{-1, -1}, {1, -1}}}, ContourPlot[
  First[ResourceFunction["PointLineDistance"][{x, y}, line]] == ResourceFunction["RealEuclideanDistance"][{x, y}, point] // Evaluate, {x, -3, 3}, {y, -3, 3}, Epilog -> {RGBColor[
    0.922526, 0.385626, 0.209179], {Point[point], InfiniteLine[line]}}]]
Out[19]=

Version History

  • 1.0.0 – 18 April 2022

Related Resources

License Information