Last active
December 28, 2015 19:59
-
-
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.
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
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