FunProg-Scala/src/Assignment1/SquareRoot.sc

19 lines
428 B
Scala

import scala.annotation.tailrec
def THRESHOLD: Double = 0.0001
def sqr(x: Double): Double = x * x
def isGoodEnough(x: Double): Boolean = if (x < 0) x > THRESHOLD else x < THRESHOLD
def improve(x: Double, approx: Double) = approx - (sqr(approx) - x) / (2 * approx)
@tailrec
def sqrt(x: Double, approx: Double): Double = if (
isGoodEnough(sqr(approx) - x)
) {
approx
} else {
sqrt(x, improve(x, approx))
}
sqrt(612, 10)