matlab二分法求方程的根_二分法求解方程的根(matlab)

matlab二分法求方程的根_二分法求解方程的根(matlab)_第1张图片
function [c, err, yc] =  bisect(f,a,b,delta)
%=================input==================================
%-f is the function input as a sting 'f'
%-a and b are the left and right end points
%-delta is the tolerance
%=================output=================================
%-c is the zero
%yc = f(c)
%err is the error estimate for c
%========================================================
% 计算区间端点a,b的函数值
ya = feval(f,a);
yb = feval(f,b);
% 如果同号,则无零点
if ya*yb >0
    break
end
% 根据误差delta推算迭代次数(这是解析推出的)
max1 = 1+round((log(b-a)-log(delta))/log(2));
% 开始循环
for k = 1:max1
   %计算a,b的中点
    c = (a+b)/2;
    %计算c的函数值
    yc=feval(f,c);
    % 若c的函数值为0,则c为零点
    if yc == 0
        a = c;
        b = c;
    % 若b,c的函数值同号,则收缩b为c
    elseif yb*yc > 0
        b=c;
        yb=yc;
    % 若a,c的函数值同号,则收缩a为c
    else
        a = c;
        ya = yc;
    end
    % 若a,b差值小于误差限,则停止
    if b-a

你可能感兴趣的:(matlab二分法求方程的根)