rational_approximations.sf 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 16 January 2019
  4. # https://github.com/trizen
  5. # Simple and efficient algorithm for finding the first continued-fraction convergents to a given real constant.
  6. # Continued-fraction convergents for PI:
  7. # https://oeis.org/A002485
  8. # https://oeis.org/A002486
  9. # See also:
  10. # https://en.wikipedia.org/wiki/Continued_fraction
  11. func rational_approximations (x, callback, first = 10) {
  12. x = x.float || return nil
  13. var (n1, n2) = (0, 1)
  14. var (d1, d2) = (1, 0)
  15. var f = x
  16. first.times {
  17. var z = f.int
  18. n1 += (n2 * z)
  19. d1 += (d2 * z)
  20. (n1, n2) = (n2, n1)
  21. (d1, d2) = (d2, d1)
  22. callback(n2 / d2);
  23. f -= z
  24. f.is_zero && break
  25. f = 1/f
  26. }
  27. }
  28. var x = Num.pi
  29. var f = func (q) { say "PI =~ #{q.as_rat}" }
  30. rational_approximations(x, f, 20)
  31. __END__
  32. PI =~ 3
  33. PI =~ 22/7
  34. PI =~ 333/106
  35. PI =~ 355/113
  36. PI =~ 103993/33102
  37. PI =~ 104348/33215
  38. PI =~ 208341/66317
  39. PI =~ 312689/99532
  40. PI =~ 833719/265381
  41. PI =~ 1146408/364913
  42. PI =~ 4272943/1360120
  43. PI =~ 5419351/1725033
  44. PI =~ 80143857/25510582
  45. PI =~ 165707065/52746197
  46. PI =~ 245850922/78256779
  47. PI =~ 411557987/131002976
  48. PI =~ 1068966896/340262731
  49. PI =~ 2549491779/811528438
  50. PI =~ 6167950454/1963319607
  51. PI =~ 14885392687/4738167652