polynomial_iterpolation.pl 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/perl
  2. # Polynomial interpolation:
  3. # find the polynomial of lowest possible degree that passes through all the points of a given dataset.
  4. # See also:
  5. # https://en.wikipedia.org/wiki/Vandermonde_matrix
  6. # https://en.wikipedia.org/wiki/Polynomial_interpolation
  7. use 5.014;
  8. use lib qw(../lib);
  9. use experimental qw(signatures);
  10. use Math::MatrixLUP;
  11. use Math::AnyNum qw(ipow sum);
  12. # A sequence of n numbers
  13. my @v = (35, 85, 102, 137, 120);
  14. # Create a new nXn Vandermonde matrix
  15. my $A = Math::MatrixLUP->build(scalar(@v), sub ($i, $j) {
  16. ipow($i, $j);
  17. }
  18. );
  19. my $S = $A->solve(\@v);
  20. say "Coefficients: [", join(', ', @$S), "]";
  21. say "Polynomial : ", join(' + ', map { "($S->[$_] * x^$_)" } 0 .. $#{$S});
  22. say "Terms : ", join(', ', map {my $x = $_; sum(map { $x**$_ * $S->[$_] } 0 .. $#{$S})} 0 .. $#v);
  23. __END__
  24. Coefficients: [35, 455/4, -2339/24, 155/4, -121/24]
  25. Polynomial : (35 * x^0) + (455/4 * x^1) + (-2339/24 * x^2) + (155/4 * x^3) + (-121/24 * x^4)
  26. Terms : 35, 85, 102, 137, 120