Created
June 5, 2012 13:06
-
-
Save hpcx82/2874854 to your computer and use it in GitHub Desktop.
Great common dividor
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 sqrtTest extends App | |
{ | |
def sqrt(x: Double) = | |
{ | |
def sqrtIter(guess: Double): Double = | |
{ | |
if(isGoodEnough(guess)) guess | |
else sqrtIter(improve(guess)) | |
} | |
def improve(guess: Double) = | |
(guess + x / guess) / 2 | |
def isGoodEnough(guess: Double) = | |
abs(square(guess) - x) < 0.001 | |
def abs(value: Double) = if(value < 0) -value else value | |
def square(value: Double) = value * value | |
sqrtIter(1.0) | |
} | |
println(sqrt(2)) | |
println(sqrt(3)) | |
println(sqrt(4)) | |
println(sqrt(10)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment