Or, you could go fancy with map and reduce:

use strict; use warnings; use List::Util q(reduce); sub xdi { my ($x, $d, $i) = @_; reduce{ $a*$b }map{ $_==$i || $d - $x->[$_] }keys @$x } sub lagc { my ($x, $f) = @_; [map{ $f->[$_] / xdi($x,$x->[$_],$_) }keys @$x] } sub lagx { my ($x, $L, $x0) = @_; reduce{ $a+$b }map{ $L->[$_] * xdi($x,$x0,$_) }keys @$x }

Consider also using bigrat if exact interpolation is sought.

Update. Same thing with sample gnuplot.

use Chart::Gnuplot; use List::Util q(reduce); sub xdi { my ($x, $d, $i) = @_; reduce{ $a*$b }map{ $_==$i || $d - $x->[$_] }keys @$x } sub lagc { my ($x, $f) = @_; [map{ $f->[$_] / xdi($x,$x->[$_],$_) }keys @$x] } sub lagx { my ($x, $L, $x0) = @_; reduce{ $a+$b }map{ $L->[$_] * xdi($x,$x0,$_) }keys @$x } my $x = [-10 .. 10]; my $f = [map { $_/25 + sin $_ } @$x]; my $LC = lagc $x, $f; my $xx = [map { $x->[0] + ($x->[-1] - $x->[0]) * $_/500 } -30 .. 530]; my $ff = [map { lagx $x, $LC, $_ } @$xx]; my $pts0 = Chart::Gnuplot::DataSet->new(xdata => $x, ydata => $f, styl +e => "points"); my $pts = Chart::Gnuplot::DataSet->new(xdata => $xx, ydata => $ff, sty +le => "lines"); Chart::Gnuplot->new(title => "f(x)", output => "plot.ps")->plot2d($pts +0, $pts);

Final note: Math::Polynomial can perform Lagrange interpolation, so there's probably little reason to roll your own module.


In reply to Re: Lagrange Polynomials in Perl by oiskuu
in thread Lagrange Polynomials in Perl by Mascasc

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.