How can i put a stopping criterion for this bisection method code in matlab?

2 views (last 30 days)
I want to put a stopping criterion of 2% in my code where, once I run the code, the result will stop if the relative error r_e is equal to 2%.
I need help on where should I put commands and how to do it
here's my code
f_x= @(x)sin(5*x)+cos(2*x)
p_old = 0; % give an initial value to it
x_l =2; x_u = 10;
n = 20;
for i=1:n
f_l = f_x(x_l);
f_u = f_x(x_u);
p = (x_l+x_u)/2;
f_m = f_x(p);
if (f_l*f_m)<0
x_u=p;
elseif (f_u*f_m)<0
x_l=p;
end
r_e = abs((p-p_old)/(p));
p_old = p; % assign the p_old after relative error
table(i, :)={i-1 p r_e};
fprintf('%d %d %d \n', table{i, :});
end

Answers (2)

Ghazwan
Ghazwan on 8 Oct 2022
The code for the bisection method is available here
https://www.mathworks.com/matlabcentral/fileexchange/72478-bisection-method

Torsten
Torsten on 8 Oct 2022
Edited: Torsten on 8 Oct 2022
f_x= @(x)sin(5*x)+cos(2*x);
p_old = 0; % give an initial value to it
x_l =2; x_u = 10;
x=x_l:0.01:x_u;
hold on
plot(x,f_x(x))
n = 20;
eps = 1e-6;
for i=1:n
f_l = f_x(x_l);
f_u = f_x(x_u);
p = (x_l+x_u)/2;
f_m = f_x(p);
if (f_l*f_m)<0
x_u=p;
elseif (f_u*f_m)<0
x_l=p;
end
plot(p,f_x(p),'o')
r_e = abs((p-p_old)/(p));
if r_e < eps
break
end
p_old = p; % assign the p_old after relative error
table(i, :)={i-1 p r_e};
fprintf('%d %d %d \n', table{i, :});
end
0 6 1 1 8 2.500000e-01 2 9 1.111111e-01 3 8.500000e+00 5.882353e-02 4 8.750000e+00 2.857143e-02 5 8.875000e+00 1.408451e-02 6 8.812500e+00 7.092199e-03 7 8.781250e+00 3.558719e-03 8 8.765625e+00 1.782531e-03 9 8.757812e+00 8.920607e-04 10 8.753906e+00 4.462294e-04 11 8.751953e+00 2.231645e-04 12 8.750977e+00 1.115947e-04 13 8.751465e+00 5.579423e-05 14 8.751709e+00 2.789634e-05 15 8.751587e+00 1.394836e-05 16 8.751526e+00 6.974230e-06 17 8.751556e+00 3.487103e-06 18 8.751572e+00 1.743548e-06
hold off

Categories

Find more on Financial Toolbox in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!