![8b97ab4e3b579e2a32db52cf5e20f668.png](https://img-blog.csdnimg.cn/img_convert/8b97ab4e3b579e2a32db52cf5e20f668.png)
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<delta
break
end
end
%最后计算一下,c及其函数值,误差
c=(a+b)/2;
err = abs(b-a);
yc = feval(f,c);