trying with bisection method to create a function that finds the root of an equation, approximated error, and numbers of iteration
Show older comments
So i did my code in the following way shown below; however, the way that my codes decided to stop the loop and output the root is by comparing if F(xr)==0 or not; however, i want to add another term which is the "approximated error" term that is to compare with a desired maximum error. So, once the Ea <= Emax, the loop is ended. The Ea should be calculated as (current approximation - previous approximation)/ current approximation; however, this is the part i do not know how to code. Could you help me with it? Any help would be really appreciated!! Thanks.
function root= bisection(fun, lb, ub,iter_max)
flb=fun(lb); % find the f(lb) value
fub=fun(ub); % find the f(ub) value
i=0; % the initial iteration
%now to test if there is a root within the uppper and lower limits
if flb*fub>0
disp('termination type 1: there is no root within bracket')
end
for i= 1: iter_max
i= i+1;
xr= (lb+ub)/2;
fxr=fun(xr);
if i >= iter_max
disp('termination type 0: algorithm terminated due to maximum interations')
break
elseif fxr==0 % test if this is the case where xr is directly the root
root= xr;
disp('this is the root')
break
end
% if none of above is met, then process the commands below
if fxr*flb>0
lb=xr;
else
ub=xr;
end
% after 1 loop, the program jumps back to the beginning
end
fprintf('The iterations taken is: %d', i)
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!