2015-09-27 38 views
0

我写了这个脚本来测试割线法在MATLAB误区与此MATLAB代码

%Test of the Secant Method 

function secantm1(x0,x1) 

    tol=10^-6; % tolerance 
    itmax=1000; % max number of iterations 
    itnum=0; % iterations counter 


    disp([itnum,x0,x1]) 
    x2=x1-f1(x1)*((x1-x0)/f1(x1)-f1(x0)); 
    itnum=itnum+1; 
    disp([itnum,x1,abs((x0-x1)/x0)]) 

    while abs((x1-x2)/x1)>tol && itnum<itmax 
     x0=x1; % I think here is mistake 
     x1=x2; 
     x2=x1-f1(x1)*((x1-x0)/f1(x1)-f1(x0)); 
     itnum=itnum+1; 
     disp([itnum,x1,abs((x1-x2)/x1),x2]) 
    end 

end 


function y=f1(x) 
y=x^3+x-3; 
end 
function y=f2(x) 
    y=x-tan(x); 
end 

但事实是,它并没有跑,我曾指出,我认为是错误的,但我不太确定我是否正确,我该如何解决。

有人可以帮我解决这个错误吗?

的事情是,当我输入F1我希望能得到像1.23 ...但这种方法不收敛,与其他功能我预计不会收敛

当我运行它,它给了我下面的:

secantm1(1,2)

0  1  2 


1  2  1 

1.0E + 03 *

0.0020 -0.0060 0.2612 -1.5730 

1.0E + 11 *

0.0000 -0.0000 0.0056 8.7573 

1.0E + 45 *

0.0000 0.0000 0.0000 -2.6139 

1.0E + 172 *

0.0000 -0.0000 0.0000 -1.1995 

1.0E + 172个*

0.0000 -1.1995  Inf  Inf 

7 Inf NaN NaN 

感谢提前。

+0

为什么选择投票? – user162343

+0

好的,事情是,当我输入F1我期望得到像1.23 ...但方法不会收敛,与其他功能,我期望不会收敛 – user162343

+1

我编辑了我的帖子:) – user162343

回答

1

问题是您在迭代更新的分母中缺少一组括号。

x2=x1-f1(x1)*((x1-x0)/f1(x1)-f1(x0)); 

应该是

x2=x1-f1(x1)*((x1-x0)/(f1(x1)-f1(x0))); 

校正正割代码应该是:

function secantm1(x0,x1) 

     tol=10^-6; % tolerance 
     itmax=1000; % max number of iterations 
     itnum=0; % iterations counter 


     disp([itnum,x0,x1]) 
     x2=x1-f1(x1)*((x1-x0)/ (f1(x1)-f1(x0))); 
     itnum=itnum+1; 
     disp([itnum,x1,abs((x0-x1)/x0)]) 

     while abs((x1-x2)/x1)>tol && itnum<itmax 
      x0=x1; % This was OK 
      x1=x2; 
      x2=x1-f1(x1)*((x1-x0)/(f1(x1)-f1(x0))); 
      itnum=itnum+1; 
      disp([itnum,x1,abs((x1-x2)/x1),x2]) 
     end 
end 

这将收敛到一个结果现在:

secantm1(1 ,2)

0  1  2 

1  2  1 

2.0000 1.1250 0.0471 1.1780 

3.0000 1.1780 0.0320 1.2156 

4.0000 1.2156 0.0019 1.2134 

5.0000 1.2134 0.0000 1.2134 

6.0000 1.2134 0.0000 1.2134 
+1

非常感谢:) – user162343