简体   繁体   中英

Can someone help improve my Scala bisection answer? What is wrong?

Implement the bisection method with the following specification:

Input: Function f, values low and high, error range epsilon.
`enter code here`Precondition: low<high, f(low) and f(high) diffs on their signs; that is,
either: f(low)>0 and f(high)<0
or:     f(low)<0 and f(high)>0.
Output: x where |f(x)| < epsilon.

Test your implementation with the following input values:
f(x) = 2x^3-3x^2-17x-50
low = -10
high = 10
epsilon = 1*10^(-6)  

Run your program, print out the solution (approximation) one each iteration

My code, not sure if this is correct:

object IntervalHalving {

def main(args: Array[String]) {
  val low = -10
  val high = 10
  val epsilon = 1*10^(-6)

//top part seems correct//

//Not sure if i defined the function correctly//

  val f(x) = (x: Double) => x*x*x + x*x - 3*x-3

  val answer= halveTheInterval(f(x), low, high, epsilon)

   // print the answer
   println(answer)
}

I don't know much about scala, but val epsilon = 1*10^(-6) is probably not what you think, but rather xor(10,-6) = -16 . Use scientific notation instead: val epsilon = 1.0e-6 .

Note that

scala> val epsilon = 1e-6
epsilon: Double = 1.0E-6

The epsilon defined above evaluates to Int with value -16 :)

And

scala> val f = (x: Double) => x*x*x + x*x - 3*x-3
f: Double => Double = <function1>

instead of val f(x) = ... Consider also for instance Math.pow(x,3) .

Recall to add a closing curly bracket for object IntervalHalving .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM