summaryrefslogtreecommitdiffstats
path: root/Scala
diff options
context:
space:
mode:
Diffstat (limited to 'Scala')
-rw-r--r--Scala/sqrt/sqrt.scala24
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))
+
+}