【发布时间】:2014-10-09 14:48:29
【问题描述】:
我正在编写一个函数,该函数实现牛顿迭代以在标量函数上求根,即找到 x 使得 f(x)=0 和 x_(n+1) = x_n - [f(x_n)/ f'(x_n)]。
f1 和 f1prime 是计算 f 和 f' 的句柄,x0 是初始根估计,'tol' 是公差。我必须继续迭代直到 |f(x_n+1)|小于 tol 或者我已经超过 10^5 次迭代。并且,函数的输出是 x_n+1。 还有... f(x)=3x^4-5x^3-12x^2 其中 f'(x)=12x^3-15x^2-24x。
我当前的代码是...
f1=@(x) 3*x^4 -5*x^3 - 12*x^2;
f1prime=@(x) 12*x^3-15*x^2-24*x;
n=0;
root=x0;
while abs(f1(x(n+1))<tol ||n>10^5
x(n+1)=x(n)-f1(x(n))/fprime(x(n));
n=n+1;
end
我的代码应该通过这个测试套件,但它没有。以上代码有什么问题?
tol=1e-6;
f1=@(x) 3*x^4 -5*x^3 - 12*x^2;
f1prime=@(x) 12*x^3-15*x^2-24*x;
x0=-1;
root_correct = [-1.333333];
[root]=newtonRoot(f1,f1prime,x0,tol);
tol1=1e-4;
assert( abs(root-root_correct) < tol1 , ...
[ '\nYour output \n root = [' sprintf(' %d ',root) ']\n' ...
'Expected output \n root = [' sprintf(' %d ',root_correct) ']\n' ], ...
root,root_correct);
【问题讨论】:
-
10^5 作为迭代限制是荒谬的。牛顿法以其二次收敛而闻名。假设初始值有 1 个正确位,下一次迭代将有 2、4、8、16、32、64...正确位。因此,迭代次数最好接近 10 次而不是 100000 次。(无论如何都要留出一些余量,因为初始值可能“小于”1 个精确位。)
标签: matlab