rational_summation_of_fractions.pl 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 23 June 2016
  5. # Website: https://github.com/trizen
  6. # Rationalized summation of fractions, based on the identity:
  7. #
  8. # a c ad + bc
  9. # --- + --- = ----------
  10. # b d bd
  11. # Combining this method with memoization, results in a practical
  12. # generalized algorithm for summation of arbitrary fractions.
  13. # In addition, with this method, any infinite sum can be converted into a limit.
  14. # Example: ∞
  15. # f(n) --- 1
  16. # lim ---------- = \ ---- = e
  17. # n->∞ _n_ / n!
  18. # | | k! ---
  19. # k=0 n=0
  20. #
  21. # where: _n_
  22. # f(n+1) = (n+1)! * f(n) + | | k!
  23. # k=0
  24. # f(0) = 1
  25. #
  26. #====================================================
  27. #
  28. # Generally:
  29. #
  30. # x
  31. # ---
  32. # \ a(n) f(x)
  33. # - ------ = ------
  34. # / b(n) g(x)
  35. # ---
  36. # n=0
  37. #
  38. # where:
  39. # | f(0) = a(0)
  40. # | f(n) = b(n) * f(n-1) + a(n) * g(n-1)
  41. #
  42. # and:
  43. # | g(0) = b(0)
  44. # | g(n) = b(n) * g(n-1)
  45. use 5.010;
  46. use strict;
  47. use warnings;
  48. use Memoize qw(memoize);
  49. use Math::AnyNum qw(:overload factorial);
  50. memoize('b');
  51. memoize('f');
  52. memoize('g');
  53. my $start = 0; # start iteration from this value
  54. my $iter = 90; # number of iterations
  55. sub a {
  56. 2**$_[0];
  57. }
  58. sub b {
  59. factorial($_[0]);
  60. }
  61. sub f {
  62. my ($n) = @_;
  63. $n <= $start
  64. ? a($n)
  65. : b($n) * f($n - 1) + a($n) * g($n - 1);
  66. }
  67. sub g {
  68. my ($n) = @_;
  69. $n <= $start
  70. ? b($n)
  71. : b($n) * g($n - 1);
  72. }
  73. my $x = f($iter) / g($iter);
  74. say $x;
  75. say "e^2 =~ ", $x->as_dec(64);