Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Last active December 27, 2015 13:09
Show Gist options
  • Save animatedlew/7331273 to your computer and use it in GitHub Desktop.
Save animatedlew/7331273 to your computer and use it in GitHub Desktop.
This function uses the Newton method to estimate a square root function. The iterator starts off with a guess of 1.0. This guess is then squared to see if the difference is small enough to call it 'good.' For really large/small values this estimate is normalized before comparing it to an epsilon. The results are gradually improved by taking the …
def sqrt(x: Double): Double = {
def isGoodEnough(guess: Double): Boolean =
abs(square(guess) - x) / x < 0.001
def improve(guess: Double): Double =
(guess + x / guess) / 2
def sqrtIter(guess: Double): Double =
if (isGoodEnough(guess)) guess
else sqrtIter(improve(guess))
sqrtIter(1.0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment