summaryrefslogtreecommitdiffstats
path: root/Scala
diff options
context:
space:
mode:
Diffstat (limited to 'Scala')
-rw-r--r--Scala/sqrt/sqrt.scala19
1 files changed, 11 insertions, 8 deletions
diff --git a/Scala/sqrt/sqrt.scala b/Scala/sqrt/sqrt.scala
index 0ab9164..b99d61e 100644
--- a/Scala/sqrt/sqrt.scala
+++ b/Scala/sqrt/sqrt.scala
@@ -3,17 +3,20 @@ 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 sqrt(x: Double) = {
- def isGoodEnough(guess: Double, x: Double) =
- abs(guess * guess - x ) /x < 0.001
+ def sqrtIter(guess: Double): Double =
+ if (isGoodEnough(guess)) guess
+ else sqrtIter(improve(guess))
- def improve(guess: Double, x: Double) =
- (guess + x / guess) / 2
+ def isGoodEnough(guess: Double) =
+ abs(guess * guess - x ) /x < 0.001
- def sqrt(x: Double) = sqrtIter(1.0, x)
+ def improve(guess: Double) =
+ (guess + x / guess) / 2
+
+ sqrtIter(1.0)
+ }
println(sqrt(2))
println(sqrt(0.001))