in reply to Lagrange Polynomials in Perl

Does your program work now? What I find strange is that these lines

$LC[$i] = $f[$i]/$den; $den = 1;

are within the "$j" loop which looks wrong to me. I would write your code like this (ignoring some of the stylistic advice given so far):

use strict; use warnings; sub lagrange { my $x = shift; my $f = shift; my @LC; my $n = @$x; for (my $i=0; $i < $n; $i++) { my $den = 1; for (my $j=0; $j < $n; $j++) { next if $j == $i; $den *= $x->[$i] - $x->[$j]; } $LC[$i] = $f->[$i]/$den; } return \@LC; } sub lageval { my $x = shift; my $LC = shift; my $x0 = shift; my $n = @$x; my $sum = 0; for (my $i=0; $i<$n;$i++) { my $mult = $LC->[$i]; for (my $j = 0; $j<$n; $j++) { next if $j == $i; $mult *= $x0 - $x->[$j]; } $sum += $mult; } return $sum; } my @x = map { $_ - 2 } 0..4; my @f = map {$_**2} @x; my $LC = lagrange \@x, \@f; my $x0 = 0.5; my $y = lageval \@x, $LC, $x0; print "$x0 $y\n";

Replies are listed 'Best First'.
Re^2: Lagrange Polynomials in Perl
by Mascasc (Novice) on Apr 29, 2015 at 14:27 UTC
    It works, once I changed the arrays to array references it worked. I tested it by approximating a sine function, and was able to get very close to the small angle approximation.

      It should be exact for polynomials, correct? Have you tried that?

        It should be exact at the points you supply it, and it does work for that. Unfortunately since the algorithm only sees points and not the whole polynomial, it's a left hand doesn't know what the right hand is doing situation...and you still get some error between the points you supply. Although I have tried it with some polynomials, and it's pretty convincing.