I took a look at Imager::Graph::Util and the math does not look so good. It doesn't use parametric equations like tye has, so it will be more prone to overflow and roundoff errors. Also, it solves line intersections only, not segments.

An alternative to simplify this type of equation is to use Math::VectorReal. There's a neat formula with vector cross products to solve this problem. It tests for being outside the segment as early as it can.

use strict; use Math::VectorReal; sub Intersection { my( $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3) = @_; my $v0 = vector($x1 - $x0, $y1 - $y0, 0); my $v1 = vector($x2 - $x0, $y2 - $y0, 0); my $v2 = vector($x3 - $x2, $y3 - $y2, 0); # Take vector cross products. Only Z is nonzero. my $a = ($v0 x $v1)->z(); my $b = ($v2 x $v0)->z(); # If |beta| > 1, line intersection outside segment. # Test it this way to avoid division by zero. return undef if abs($a) > abs($b); my $beta; if ($b == 0.0) { # 0/0 case $beta = 0.0; } else { $beta = $a/$b; } # Line intersection outside segment return undef if ($beta < 0.0); # Now check in the other direction $a = ($v2 x $v1)->z(); # |beta| > 1, line intersection outside segment return undef if abs($a) > abs($b); if ($b == 0) { # 0/0 case $beta = 0.0; } else { $beta = $a/$b; } # line intersection outside other side return undef if ($beta < 0.0); # find by parametric equation $px = $x2 + $beta*($x3 - $x2); $py = $y2 + $beta*($y3 - $y2); return [$px, $py]; }

In reply to Re: Re: line segment intersection by tall_man
in thread line segment intersection by bobdeath

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.