How can i put a stopping criterion for this bisection method code in matlab?
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
Ghazwan
2022-10-8
The code for the bisection method is available here
https://www.mathworks.com/matlabcentral/fileexchange/72478-bisection-method
0 个评论
Torsten
2022-10-8
编辑:Torsten
2022-10-8
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
hold off
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Financial Toolbox 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!