diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2013-03-28 14:50:08 +0100 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-10 18:03:20 +0100 |
commit | 292a74d4b221e481dfe278feb2c2bef24df60b0b (patch) | |
tree | 193bbf2025a714ded8dfb446f3f1e7be600c6ff8 /Scala/sandbox/sqrt.scala | |
parent | 88fefcd04abc25938fac6d23b067db41910ab6ca (diff) | |
download | coursera-292a74d4b221e481dfe278feb2c2bef24df60b0b.zip coursera-292a74d4b221e481dfe278feb2c2bef24df60b0b.tar.gz |
Scala : move sqrt into sandbox and Scala : add recursion.scala
Diffstat (limited to 'Scala/sandbox/sqrt.scala')
-rw-r--r-- | Scala/sandbox/sqrt.scala | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/Scala/sandbox/sqrt.scala b/Scala/sandbox/sqrt.scala new file mode 100644 index 0000000..2544425 --- /dev/null +++ b/Scala/sandbox/sqrt.scala @@ -0,0 +1,28 @@ + +object Sqrt { + + def abs(x:Double) = if (x < 0) -x else x + + def sqrt(x: Double) = { + + def sqrtIter(guess: Double): Double = + if (isGoodEnough(guess)) guess + else sqrtIter(improve(guess)) + + def isGoodEnough(guess: Double) = + abs(guess * guess - x ) /x < 0.001 + + def improve(guess: Double) = + (guess + x / guess) / 2 + + sqrtIter(1.0) + } + + def run = + println(sqrt(2)) + println(sqrt(0.001)) + println(sqrt(0.1e-20)) + println(sqrt(1.0e20)) + println(sqrt(1.0e50)) + +} |