summaryrefslogtreecommitdiffstats
path: root/Scala/sqrt/sqrt.scala
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-03-28 12:35:18 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-10 18:03:20 +0100
commit88fefcd04abc25938fac6d23b067db41910ab6ca (patch)
tree6a7aeb29760d801d348d225979c511711f7b1489 /Scala/sqrt/sqrt.scala
parentfefed5656762a70db204539da102f29b689676bf (diff)
downloadcoursera-88fefcd04abc25938fac6d23b067db41910ab6ca.zip
coursera-88fefcd04abc25938fac6d23b067db41910ab6ca.tar.gz
Scala : improve sqrt using block and scope
Diffstat (limited to 'Scala/sqrt/sqrt.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))