How do I modify this bracketing bisection method from a 'for' loop to a 'while loop'??
์ด์ ๋๊ธ ํ์
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
๋ต๋ณ (1๊ฐ)
darova
2020๋
3์ 26์ผ
0 ๊ฐ ์ถ์ฒ
Solution

์นดํ ๊ณ ๋ฆฌ
๋์๋ง ์ผํฐ ๋ฐ File Exchange์์ Loops and Conditional Statements์ ๋ํด ์์ธํ ์์๋ณด๊ธฐ
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!