Just another Perl shrine PerlMonks

### Re: perl module or code for calculating the shortest distance between a line and a point (vector linear algebra)

by randyk (Parson)
 on Dec 30, 2009 at 17:00 UTC ( #814968=note: print w/replies, xml ) Need Help??

A general algorithm for calculating the closest distance between a line and a point is described, for example, at http://math.ucsd.edu/~wgarner/math4c/derivations/distance/distptline.htm. Here's a script that illustrates this:
```use strict;
use warnings;
# line passes through (x1, y1) and (x2, y2)
my (\$x1, \$y1) = (0, 2);
my (\$x2, \$y2) = (-2, 2);
# put it into the form y = mx + b
my \$m = (\$y2 - \$y1) / (\$x2 - \$x1);
my \$b = (\$y1 * \$x2 - \$y2 * \$x1) / (\$x2 - \$x1);
# target point is (x0, y0)
my (\$x0, \$y0) = (8, 0);
# shortest distance from line to target point
my \$d = abs( \$y0 - \$m * \$x0 - \$b) / sqrt(\$m * \$m + 1);
print "The closest distance is \$d\n";
• Comment on Re: perl module or code for calculating the shortest distance between a line and a point (vector linear algebra)

Replies are listed 'Best First'.
Re^2: perl module or code for calculating the shortest distance between a line and a point (vector linear algebra)
by spx2 (Deacon) on Jan 01, 2010 at 09:15 UTC
hi randyk,

yes, that's true, for the plane.

in his code he seems to use \$z(point) which suggests these lines and points are in 3D space. the shortest distance from a point to a line is a perpendicular on the line passing through that point. see here the development of a formula for the problem in question.

Re^2: perl module or code for calculating the shortest distance between a line and a point (vector linear algebra)
by salva (Abbot) on Jan 01, 2010 at 10:35 UTC
Your code can't handle the case where \$x2 == \$x1.

Create A New User
Node Status?
node history
Node Type: note [id://814968]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2020-06-04 05:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Do you really want to know if there is extraterrestrial life?

Results (30 votes). Check out past polls.

Notices?