quadratic_polynomial_in_terms_of_its_zeros.pl 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 09 August 2017
  4. # https://github.com/trizen
  5. # Representation of quadratic polynomials in terms of their zeros.
  6. # Let:
  7. # P(x) = a*x^2 + b*x + c
  8. # Let (m, n) be the solutions to P(x) = 0
  9. # Then:
  10. # P(x) = c * (1 - x/m) * (1 - x/n)
  11. use 5.010;
  12. use strict;
  13. use warnings;
  14. use Math::Bacovia qw(:all);
  15. use Math::AnyNum qw(isqrt);
  16. sub integer_quadratic_formula {
  17. my ($x, $y, $z) = @_;
  18. (
  19. Fraction((-$y + isqrt($y**2 - 4 * $x * $z)), (2 * $x)),
  20. Fraction((-$y - isqrt($y**2 - 4 * $x * $z)), (2 * $x)),
  21. );
  22. }
  23. my @poly = (
  24. [ 3, -15, -42],
  25. [ 20, -97, -2119],
  26. [-43, 29, 14972],
  27. );
  28. my $x = Symbol('x');
  29. foreach my $t (@poly) {
  30. my ($x1, $x2) = integer_quadratic_formula(@$t);
  31. my $expr = $t->[0] * $x**2 + $t->[1] * $x + $t->[2];
  32. my $f1 = (1 - $x / $x1);
  33. my $f2 = (1 - $x / $x2);
  34. printf("%s = %s * %s * %s\n",
  35. $expr->pretty,
  36. $f1->simple->pretty,
  37. $f2->simple->pretty,
  38. $t->[2],
  39. );
  40. }
  41. __END__
  42. ((3 * x^2) + (-15 * x) + -42) = (1 - (x/7)) * (1 - (x/-2)) * -42
  43. ((20 * x^2) + (-97 * x) + -2119) = (1 - (x/13)) * (1 - (x/(-326/40))) * -2119
  44. ((-43 * x^2) + (29 * x) + 14972) = (1 - (x/(-788/43))) * (1 - (x/19)) * 14972