Skip to content

Instantly share code, notes, and snippets.

@ryandotsmith
Created May 5, 2010 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryandotsmith/390253 to your computer and use it in GitHub Desktop.
Save ryandotsmith/390253 to your computer and use it in GitHub Desktop.
newton's method for computing sqrt
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