How do I modify this bracketing bisection method from a 'for' loop to a 'while loop'??
Show older comments
This is a bisection method for root finding the function ?(?) = ?^2 − 3.
- Modify this file from a ‘for’ loop to a while loop that has a stopping criterion when the percent relative error (obtained by multiplying the εa equation below by 100) is less than 0.01%. How many iterations did this code perform to obtain a result within 0.01% of the actual root? (Hint: remove the pause(1) line to make the algorithm run as fast as it can).

% Bracketing Bisection Method
clear all
close all
x=linspace(1,5,300)
y = x.^2-3
i=1
xl(i) = min(x)
xu(i) = max(x)
yl(i) = xl(i).^2-3
yu(i) = xu(i).^2-3
if yl(i)*yu(i)<0
for i=2:20
subplot(1,2,1)
plot(x,y,'k');hold on
plot([1 5],[0 0],'k--')
xr(i) = (xl(i-1)+xu(i-1))./2;
yr(i) = xr(i).^2-3;
yu(i) = xu(i-1).^2-3;
yl(i) = xl(i-1).^2-3;
prodleft = yl(i)*yr(i);
prodright = yr(i)*yu(i);
if prodleft <0
xu(i) = xr(i);
xl(i) = xl(i-1);
else
xl(i) = xr(i);
xu(i) = xu(i-1);
end
subplot(1,2,1)
plot([xl(i) xl(i)],[-5 25],'r:');
plot([xu(i) xu(i)],[-5 25],'r:');
axis([1 3 -2 5])
title('x_r per iteration','Fontsize',20)
xlabel('x','Fontsize',20)
ylabel('f(x)','Fontsize',20)
axis square
hold off
subplot(1,2,2)
plot(xr)
xlim([0 20])
title('x_r','Fontsize',20)
xlabel('Iteration number [-]','Fontsize',20)
ylabel('x_r','Fontsize',20)
axis square
pause(1)
end
end
Answers (1)
darova
on 26 Mar 2020
0 votes
Solution

Categories
Find more on Loops and Conditional Statements 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!