Created
December 10, 2011 03:07
-
-
Save peterc/1454432 to your computer and use it in GitHub Desktop.
Square root calculation using Newton-Raphson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Square root calculation using Newton-Raphson | |
# from Practical Programming (1968) | |
a = 256 | |
x = (1 + a) / 2.0 | |
loop do | |
ox = x | |
x = (x + a.to_f / x) / 2.0 | |
break if x >= ox | |
end | |
puts "The square root of #{a} is #{x}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I gave it a go. No significant performance gain, as far as I could tell. On the few runs I tried, it was a few percent.
All in the interests of science though since, of course, the iterative solution is quicker anyway ;-)