fractional_pi.pl 876 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 10 May 2016
  5. # Website: https://github.com/trizen
  6. # Calculate PI by computing the numerator and the denominator fraction that approaches the value of PI.
  7. # It's based on the continued fraction: n^2 / (2n+1)
  8. # See: https://oeis.org/A054766
  9. # https://oeis.org/A054765
  10. use 5.010;
  11. use strict;
  12. use warnings;
  13. use Memoize qw(memoize);
  14. use Math::AnyNum qw(:overload as_dec);
  15. no warnings 'recursion';
  16. memoize('pi_nu');
  17. memoize('pi_de');
  18. sub pi_nu {
  19. my ($n) = @_;
  20. $n < 2
  21. ? ($n == 0 ? 1 : 0)
  22. : (2 * $n - 1) * pi_nu($n - 1) + ($n - 1)**2 * pi_nu($n - 2);
  23. }
  24. sub pi_de {
  25. my ($n) = @_;
  26. $n < 2
  27. ? $n
  28. : (2 * $n - 1) * pi_de($n - 1) + ($n - 1)**2 * pi_de($n - 2);
  29. }
  30. my $prec = 1000;
  31. my $pi = as_dec(4 / (1 + pi_nu($prec) / pi_de($prec)), int($prec / 1.32));
  32. say $pi;