polynomial_regression_anynum.t 995 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!perl -T
  2. use 5.006;
  3. use strict;
  4. use warnings;
  5. use Test::More;
  6. BEGIN {
  7. eval { require Math::AnyNum };
  8. plan skip_all => "Math::AnyNum is not installed"
  9. if $@;
  10. plan skip_all => "Math::AnyNum >= 0.38 is needed"
  11. if ($Math::AnyNum::VERSION < 0.38);
  12. }
  13. plan tests => 2;
  14. use Math::MatrixLUP;
  15. use Math::AnyNum qw(:overload ipow);
  16. sub regress {
  17. my ($x, $y, $degree) = @_;
  18. my $mx = Math::MatrixLUP->build(
  19. scalar(@$x),
  20. $degree + 1,
  21. sub {
  22. my ($i, $j) = @_;
  23. ipow($x->[$i], $j);
  24. }
  25. );
  26. my $my = Math::MatrixLUP->column($y);
  27. my $r1 = $mx->transpose->mul($mx)->invert->mul($mx->transpose)->mul($my)->transpose;
  28. my $r2 = ~((~$mx * $mx)**(-1) * ~$mx * $my);
  29. return ($r1, $r2);
  30. }
  31. #<<<
  32. my ($r1, $r2) = regress(
  33. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  34. [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321],
  35. 2
  36. );
  37. #>>>
  38. is_deeply($r1->as_array, $r2->as_array);
  39. is_deeply($r1->as_array, [[1, 2, 3]]);