shouce 发表于 2015-6-4 09:25:35

解方程的二分法 matlab 程序

解方程的二分法matlab 程序( x^3-3*x^2+6*x-1=0)

% Bisection.m
function=Bisection(f,a,b,eps1,eps2,N)
fprintf('k ,a ,b ,x, f\n')
for k=1:N
    x=(a+b)/2;
    f_value=f(x);
    fprintf( '%3d, %10.9f, %10.9f, %10.9f,%10.9f,\n'...
      ,k ,a ,b ,x, f_value)
    if abs(f_value)< eps1||0.5*(b-a)<eps2
    return
    else
      if f(x)*f(a)<0
          b=x;
      else
          a=x;
      end
      if k== N
          warning ('算法超出最大迭代数!')   
      end
    end

% examlpe7.m
a=0; b=1;
eps1=1e-4;eps2=1e-4;
N=300;
f=@ (x) (x^3-3*x^2+6*x-1);
Hfun=@Bisection;
= feval(Hfun, f,a,b,eps1,eps2,N);

运行结果
>> examlpe7
k ,a ,b ,x, f
1, 0.000000000, 1.000000000, 0.500000000,1.375000000,
2, 0.000000000, 0.500000000, 0.250000000,0.328125000,
3, 0.000000000, 0.250000000, 0.125000000,-0.294921875,
4, 0.125000000, 0.250000000, 0.187500000,0.026123047,
5, 0.125000000, 0.187500000, 0.156250000,-0.131927490,
6, 0.156250000, 0.187500000, 0.171875000,-0.052295685,
7, 0.171875000, 0.187500000, 0.179687500,-0.012936115,
8, 0.179687500, 0.187500000, 0.183593750,0.006630838,
9, 0.179687500, 0.183593750, 0.181640625,-0.003143273,
10, 0.181640625, 0.183593750, 0.182617188,0.001746121,
11, 0.181640625, 0.182617188, 0.182128906,-0.000697991,
12, 0.182128906, 0.182617188, 0.182373047,0.000524211,
13, 0.182128906, 0.182373047, 0.182250977,-0.000086854,


页: [1]
查看完整版本: 解方程的二分法 matlab 程序