Frage

package week1
import math.abs
object newton {
    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  < 0.001)

    def improve(guess: Double, x: Double) =
        (guess + x/guess)/2

    def sqrt (x:Double)= sqrtIter(1.0,x)

}

at line

abs (guess*guess - x <0.001)

eclipse shows the following error

type mismatch; found : Boolean required: Double newton.sc /progfun/src/week1 line 10 Scala Problem

How do I solve this? It's my first time running scala and I'm using the exact code from Functional Programmming class currently going on in Coursera.

War es hilfreich?

Lösung

This line

abs (guess*guess - x <0.001)

returns a boolean, since it first evaluates guess*guess - x, and than compares it to 0.001.

You should do this

abs (guess*guess - x) < 0.001
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top