A first problem in your code is that the returned variable "root" does not always take a value. A second one is the "i= i+1;". i is the index of the loop so there is no need to increase it. Furthermore it would be good to test also if one of the initial limits is the root. An example of what you want do to is the following.
function root= bisection(fun, lb, ub,iter_max, Emax)
flb=fun(lb);
fub=fun(ub);
i=0;
if flb==0
root=lb;
fprintf('The root is: %5.3f \n', root)
return
end
if fub==0
root=ub;
fprintf('The root is: %5.3f \n', root)
return
end
if flb*fub>0
disp('termination type 1: there is no root within bracket')
root=NaN;
return
end
root= (lb+ub)/2;
for i=1:iter_max
rootPrevious=root;
fxr=fun(root);
if i >= iter_max
disp('termination type 0: algorithm terminated due to maximum interations')
break
elseif fxr==0
disp('this is the root')
break
end
if fxr*flb>0
lb=root;
else
ub=root;
end
root= (lb+ub)/2;
error=abs((root-rootPrevious)/root);
if error<Emax
break
end
end
fprintf('The iterations taken is: %d \n', i)
fprintf('The root is: %5.3f \n', root)
Best Answer