generalized_continued_fraction_parts_iter.sf 996 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 23 January 2018
  4. # https://github.com/trizen
  5. # Numerical evaluation of a generalized continued fraction, computing
  6. # the numerator and the denominator separately (iterative algorithm).
  7. #
  8. ## Compute the numerator of the continued fraction
  9. #
  10. func cfrac_num(from, to, num, den) is cached {
  11. var (f1, f2) = (1, 0)
  12. for ((); to > from; ++from) {
  13. (f1, f2) = (f2, den.run(from)*f2 + num.run(from)*f1)
  14. }
  15. return f2
  16. }
  17. #
  18. ## Compute the denominator of the continued fraction
  19. #
  20. func cfrac_den(from, to, num, den) is cached {
  21. var (f1, f2) = (0, 1)
  22. for ((); to > from; ++from) {
  23. (f1, f2) = (f2, den.run(from)*f2 + num.run(from)*f1)
  24. }
  25. return f2
  26. }
  27. #
  28. ## Example for [n=1..Infinity, n^2 / (2n+1)] = 4/Pi - 1
  29. #
  30. var num = {|n| n**2 }
  31. var den = {|n| 2*n + 1 }
  32. var a = cfrac_num(1, 30, num, den)
  33. var b = cfrac_den(1, 30, num, den)
  34. say "Numerator = #{a}"
  35. say "Denominator = #{b}"
  36. say "Expansion = #{a/b}"