Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
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??


in reply to perl module or code for calculating the shortest distance between a line and a point (vector linear algebra)

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)
Download Code
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 (Chaplain) 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.

Log In?
Username:
Password:

What's my password?
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 perusing the Monastery: (12)
As of 2015-07-28 07:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (253 votes), past polls