使用以下规范实现bisection方法:
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)
}
答案 0 :(得分:0)
我对scala了解不多,但val epsilon = 1*10^(-6)
可能不是您的想法,而是xor(10,-6) = -16
。请改用科学记数法:val epsilon = 1.0e-6
。
答案 1 :(得分: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
添加一个结束花括号。