0

使用以下规范实现二分法:

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

我的代码,不确定这是否正确:

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)
}
4

2 回答 2

0

注意

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

epsilon上面定义的计算结果Int-16 :)

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

而不是val f(x) = ...考虑也例如Math.pow(x,3)

回想一下为 . 添加一个右大括号object IntervalHalving

于 2014-04-29T08:12:07.590 回答
0

我对scala了解不多,但val epsilon = 1*10^(-6)可能不是你想的那样,而是xor(10,-6) = -16. 请改用科学记数法:val epsilon = 1.0e-6.

于 2014-04-29T00:35:06.710 回答