unreduced_continued_fractions.sf 755 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 02 December 2016
  5. # https://github.com/trizen
  6. # Recursive evaluation of continued fractions rationally,
  7. # by computing the numerator and the denominator individually.
  8. # For every continued fraction, we have the following relation:
  9. #
  10. # n
  11. # | / a(k) kn(n)
  12. # |/ ----- = -------
  13. # | \ b(k) kd(n)
  14. # k=0
  15. #
  16. ## Example for:
  17. ## K(n^2 / (2n+1)) = 4/Pi - 1
  18. #
  19. func a(n) { n**2 }
  20. func b(n) { 2*n + 1 }
  21. func kn(n) is cached {
  22. n < 2 ? (n == 0 ? 1 : 0)
  23. : (b(n - 1)*kn(n - 1) + a(n - 1)*kn(n - 2))
  24. }
  25. func kd(n) is cached {
  26. n < 2 ? n
  27. : (b(n - 1)*kd(n - 1) + a(n - 1)*kd(n - 2))
  28. }
  29. for n in (0 .. 10) {
  30. printf("%2d. %20s %-20s\n", n, kn(n), kd(n));
  31. }