generalized_continued_fraction.sf 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 18 January 2018
  4. # https://github.com/trizen
  5. # Numerical evaluation of a generalized continued fraction.
  6. # See also:
  7. # https://en.wikipedia.org/wiki/Generalized_continued_fraction
  8. #
  9. ## Compute the continued fraction numerically
  10. #
  11. func contfrac2num (from, to, num, den) {
  12. return 0 if (from > to)
  13. num.run(from) / (den.run(from) + __FUNC__(from + 1, to, num, den))
  14. }
  15. #
  16. ## Compute only the numerator of the continued fraction
  17. #
  18. func cfrac_num(from, to, num, den) is cached {
  19. return 1 if (to == from-1)
  20. return 0 if (to == from)
  21. den.run(to-1)*__FUNC__(from, to-1, num, den) + num.run(to-1)*__FUNC__(from, to-2, num, den)
  22. }
  23. #
  24. ## Compute only the denominator of the continued fraction
  25. #
  26. func cfrac_den(from, to, num, den) is cached {
  27. return 1 if (to == from)
  28. return 0 if (to == from-1)
  29. den.run(to-1)*__FUNC__(from, to-1, num, den) + num.run(to-1)*__FUNC__(from, to-2, num, den)
  30. }
  31. var from = float(1)
  32. var to = float(100)
  33. #
  34. ## Example for [n=1..Infinity, n^2 / (2n+1)] = 4/Pi - 1
  35. #
  36. var num = {|n| n**2 }
  37. var den = {|n| 2*n + 1 }
  38. say contfrac2num(from, to, num, den)
  39. say contfrac2num(from, to+100, num, den)
  40. say contfrac2num(from, to+1000, num, den)
  41. say contfrac2num(from, to+2000, num, den)
  42. var a = cfrac_num(from, 30, num, den)
  43. var b = cfrac_den(from, 30, num, den)
  44. say "Numerator = #{a}"
  45. say "Denominator = #{b}"
  46. say "Expansion = #{a/b}"