Last active
December 27, 2015 13:09
-
-
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 …
This file contains hidden or 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
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