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 | |
by hdb (Monsignor) on Apr 29, 2015 at 14:39 UTC | |
by Mascasc (Novice) on Apr 29, 2015 at 14:53 UTC | |
by hdb (Monsignor) on Apr 29, 2015 at 14:59 UTC | |
by Mascasc (Novice) on Apr 29, 2015 at 15:50 UTC |