diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2013-03-28 12:33:35 +0100 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-10 18:03:20 +0100 |
commit | fefed5656762a70db204539da102f29b689676bf (patch) | |
tree | fda307524c4b1bf6d791df78eaa2828318c05617 /Scala/sqrt/sqrt.scala | |
parent | dcdc4d3e6ed08f37f7acd75c79ddea607d2e8e2a (diff) | |
download | coursera-fefed5656762a70db204539da102f29b689676bf.zip coursera-fefed5656762a70db204539da102f29b689676bf.tar.gz |
Scala : add sqrt.scala
Diffstat (limited to 'Scala/sqrt/sqrt.scala')
-rw-r--r-- | Scala/sqrt/sqrt.scala | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/Scala/sqrt/sqrt.scala b/Scala/sqrt/sqrt.scala new file mode 100644 index 0000000..0ab9164 --- /dev/null +++ b/Scala/sqrt/sqrt.scala @@ -0,0 +1,24 @@ + +object Main extends App { + + def abs(x:Double) = if (x < 0) -x else x + + def sqrtIter(guess: Double, x: Double): Double = + if (isGoodEnough(guess, x)) guess + else sqrtIter(improve(guess, x), x) + + def isGoodEnough(guess: Double, x: Double) = + abs(guess * guess - x ) /x < 0.001 + + def improve(guess: Double, x: Double) = + (guess + x / guess) / 2 + + def sqrt(x: Double) = sqrtIter(1.0, x) + + println(sqrt(2)) + println(sqrt(0.001)) + println(sqrt(0.1e-20)) + println(sqrt(1.0e20)) + println(sqrt(1.0e50)) + +} |