Skip to content

Instantly share code, notes, and snippets.

@GMadorell
Last active December 28, 2015 19:59
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 GMadorell/7554384 to your computer and use it in GitHub Desktop.
Save GMadorell/7554384 to your computer and use it in GitHub Desktop.
A implementation of Newton's method for calculating the sqrt() of a number.
def isGoodEnough(guess: Double, x: Double) = {
math.abs(guess * guess - x) / x < 0.0001
}
def improve(guess: Double, x: Double): Double = {
(guess + x / guess) / 2
}
def sqrtIter(guess: Double, x: Double): Double = {
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
}
def sqrt(x: Double): Double = {
sqrtIter(1.0, x)
}
sqrt(1)
sqrt(2)
sqrt(5)
sqrt(1e-6)
sqrt(1e60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment