continued_fractions_for_nth_roots.sf 843 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 03 February 2019
  4. # https://github.com/trizen
  5. # Approximate n-th roots, using continued fractions.
  6. # See also:
  7. # https://en.wikipedia.org/wiki/Generalized_continued_fraction#Roots_of_positive_numbers
  8. func cfrac_nth_root (z, m, n, y, r, k=1) {
  9. return 0 if (r <= 0)
  10. (k² * n² - m²) * y² / ((2*k + 1)*n*(2*z - y) - __FUNC__(z, m, n, y, r - 1, k+1))
  11. }
  12. func nth_root(z, n, r = 100) {
  13. var (x, y) = z.irootrem(n)
  14. var m = 1
  15. var t = cfrac_nth_root(z, m, n, y, r)
  16. x**m + ((2 * x * m * y) / (n*(2*z - y) - m*y - t))
  17. }
  18. say nth_root(1234, 2) #=> 35.12833614050059160587031162535630676454048547878
  19. say nth_root(12345, 3) #=> 23.11161874980726868087197332958829017451713700262
  20. say nth_root(123456, 5) #=> 10.43043546409766483375317008568663847055013893731