Bisection method add iteration table into my code
Show older comments
function m = bisection(f, low, high, tol)
disp('Bisection Method');
% Evaluate both ends of the interval
y1 = feval(f, low);
y2 = feval(f, high);
i = 0;
% Display error and finish if signs are not different
if y1 * y2 > 0
disp('Have not found a change in sign. Will not continue...');
return
end
% Work with the limits modifying them until you find
% a function close enough to zero.
disp('Iter low high x0');
while (abs(high - low) >= tol)
i = i + 1;
% Find a new value to be tested as a root
m = (high + low)/2;
y3 = feval(f, m);
if y3 == 0
fprintf('Root at x = %f \n\n', m);
return
end
fprintf('%2i \t %f \t %f \t %f \n', i-1, low, high, m);
% Update the limits
if y1 * y3 > 0
low = m;
y1 = y3;
else
high = m;
end
end
% Show the last approximation considering the tolerance
w = feval(f, m);
fprintf('\n x = %f produces f(x) = %f \n %i iterations\n', m, y3, i-1);
fprintf(' Approximation with tolerance = %f \n', tol);
If it is important my code works by entering variables into command line like:
my_fun = @(x) exp(x) - 3*x;
low = 0;
high = 1;
tolerance = .00001;
x = bisection(my_fun, low, high, tolerance);
I want to ask how could I add an iterations graphic into my code? I want to see a x value at each iteration.
Answers (1)
Something like this?
my_fun = @(x) exp(x) - 3*x;
low = 0;
high = 1;
tolerance = .00001;
[x, x0] = bisection(my_fun, low, high, tolerance); %%%%%%%%%%%%%%%%%
plot(0:numel(x0)-1,x0,'*--'),grid %%%%%%%%%%%%%%%%%%%%%%%%
function [m, x0] = bisection(f, low, high, tol)
disp('Bisection Method');
% Evaluate both ends of the interval
y1 = feval(f, low);
y2 = feval(f, high);
i = 0;
% Display error and finish if signs are not different
if y1 * y2 > 0
disp('Have not found a change in sign. Will not continue...');
return
end
% Work with the limits modifying them until you find
% a function close enough to zero.
disp('Iter low high x0');
while (abs(high - low) >= tol)
i = i + 1;
% Find a new value to be tested as a root
m = (high + low)/2;
y3 = feval(f, m);
if y3 == 0
fprintf('Root at x = %f \n\n', m);
return
end
fprintf('%2i \t %f \t %f \t %f \n', i-1, low, high, m);
x0(i) = m; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Update the limits
if y1 * y3 > 0
low = m;
y1 = y3;
else
high = m;
end
end
% Show the last approximation considering the tolerance
w = feval(f, m);
fprintf('\n x = %f produces f(x) = %f \n %i iterations\n', m, y3, i-1);
fprintf(' Approximation with tolerance = %f \n', tol);
end
Categories
Find more on Code Performance 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!