polynomial_interpolation.pl 1.1 KB

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