Created
September 19, 2012 06:22
-
-
Save f3nry/3747995 to your computer and use it in GitHub Desktop.
Square Roots in Scala
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
object session { | |
def sqrt(x: Double) = { | |
def abs(x: Double) = if (x < 0) -x else x | |
def sqrtIter(guess: Double): Double = | |
if(isGoodEnough(guess)) guess | |
else sqrtIter(improve(guess)) | |
def isGoodEnough(guess: Double): Boolean = | |
abs(guess * guess - x) / x < 0.001 | |
def improve(guess: Double) = | |
(guess + x / guess) / 2 | |
sqrtIter(1.0, x) | |
} //> sqrt: (x: Double)Double | |
sqrt(2) //> res0: Double = 1.4142156862745097 | |
sqrt(4) //> res1: Double = 2.000609756097561 | |
sqrt(1e-6) //> res2: Double = 0.0010000001533016628 | |
sqrt(1e60) //> res3: Double = 1.0000788456669446E30 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment