pell_method_for_square_roots.sf 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 04 February 2019
  4. # https://github.com/trizen
  5. # Approximate square roots, using Pell's method.
  6. # See also:
  7. # https://rosettacode.org/wiki/Pell%27s_equation
  8. # https://en.wikipedia.org/wiki/Pell%27s_equation
  9. # https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
  10. func pell_square_root(n, eps=1e-22) {
  11. var x = n.isqrt
  12. var y = x
  13. var z = 1
  14. var r = 2*x
  15. var (e1, e2) = (1, 0)
  16. var (f1, f2) = (0, 1)
  17. loop {
  18. y = (r*z - y)
  19. z = ((n - y*y) / z)
  20. r = round((x + y) / z) # floor() also works
  21. (e1, e2) = (e2, r*e2 + e1)
  22. (f1, f2) = (f2, r*f2 + f1)
  23. var A = (e2 + x*f2)
  24. var B = f2
  25. if (abs((A/B)**2 - n) <= eps) {
  26. return A/B
  27. }
  28. }
  29. }
  30. for n in [61, 109, 181, 277] {
  31. var s = pell_square_root(n)
  32. say "sqrt(#{'%3d' % n}) =~ #{s.as_rat} =~ #{s}"
  33. }
  34. __END__
  35. sqrt( 61) =~ 5380205503727/688864726095 =~ 7.81024967590665439412972327539046655850673601909
  36. sqrt(109) =~ 5886776254306/563850903159 =~ 10.4403065089105501797577550769986386680615397574
  37. sqrt(181) =~ 2900300962727/215577672795 =~ 13.45362404707371031716308866094140080774035985437
  38. sqrt(277) =~ 4157003026204/249770104837 =~ 16.64331697709323806892821623002200061329832127014