Created
May 5, 2010 01:23
-
-
Save ryandotsmith/390253 to your computer and use it in GitHub Desktop.
newton's method for computing sqrt
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
PRECISION = 0.0001 | |
def newtonian_guess( guess,fx,fdx ) | |
loop do | |
better_guess = guess - ( fx.call( guess ).to_f / fdx.call( guess ).to_f ) | |
return better_guess if ((better_guess - guess).abs <= PRECISION) | |
guess = better_guess | |
end | |
end | |
def sqrt( num ) | |
guess = num/2 | |
return newtonian_guess( guess, lambda {|x| (x**2)-num } ,lambda {|x| 2*x }) | |
end | |
class Float | |
def to_sqrt | |
sqrt( self ) | |
end | |
end | |
p 2.0.to_sqrt | |
# => 1.41421356237469 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment