博大广阔 发表于 2012-6-6 20:47

二分法求方程的零解

function bisect0=bisect(xl,xu,es)
clc
clear all
fun=inline('sin(10*x)+cos(3*x)','x'); XL=3;Xu=5;
max_iter=50;es=0.001; iter=1;

XX=possible_root(fun,XL,Xu,0.1)
m_root=size(XX,1);
for number=1:m_root
xl=XX(number,1);xu=XX(number,2);
fl=fun(xl);xr=xl;
while iter<max_iter
    xrold=xr;
    xr=(xl+xu)/2;
    fr=fun(xr);
    if xr~=0                     % 计算相对误差
      ea=abs((xr-xrold)/xr)*100;
    end
    %%%%%%%%%%%%%%%%%%%%%区间变换%%%%%%%%%%%
    test=fl*fr;
    if test<0
      xu=xr;
    elseif test>0
      xl=xr;
      fl=fr;
    else ea=0;
    end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if ea<es
      break;
    end
    bisect(number,:)=xr;
    iter=iter+1;
end
end
bisect=bisect
error=fun(bisect)
end

function xr=possible_root(fun,xl,xu,size)

n=xl:size:xu;m=1;
for cnt=1:length(n)-1;
    test=fun(n(cnt))*fun(n(cnt+1));
    if test<0
       xr1(m,:)=;
       m=m+1;
    end
end
xr=xr1;
end

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