From fefed5656762a70db204539da102f29b689676bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Zurcher?= Date: Thu, 28 Mar 2013 12:33:35 +0100 Subject: Scala : add sqrt.scala --- Scala/sqrt/sqrt.scala | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Scala/sqrt/sqrt.scala 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)) + +} -- cgit v1.1-2-g2b99