Bisection Method Code Help
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1113385/image.png)
Help with my code. Only spits out one value.
Function File:
%Script File:
func=@(x) sin(10*x)+cos(3*x);
xl=3; xu=5;
x=bisection1(func,xl,xu)
function root=bisection1(func,x1,xu)
xr=x1;es=.0001;
i=0;
while i<6
i=i+1;
xrold=xr;
xr=(x1+xu)/2;
if xr~=0
ea=abs((xr-xrold)/xr)*100;
root=xr
else
ea=100;
root=xr
end
if func(x1)*func(xr)<0
xu=xr;
root=xr
elseif func(x1)*func(xr)>0
x1=xr;
root=xr
else
ea=0;
root=xr
end
if ea<=es,break,end
end
root=xr;
end
2 commentaires
Réponses (1)
Torsten
le 31 Août 2022
I didn't check whether there is a programming error in bisection1. In comparison to fzero it's very inexact - that's for sure.
format long
func=@(x) sin(10*x)+cos(3*x);
xl=3.2; xu=3.3;
x(1)=bisection1(func,xl,xu);
x1(1)=fzero(func,[xl,xu]);
xl=3.3; xu=3.4;
x(2)=bisection1(func,xl,xu);
x1(2)=fzero(func,[xl,xu]);
xl=3.6; xu=3.8;
x(3)=bisection1(func,xl,xu);
x1(3)=fzero(func,[xl,xu]);
xl=4.15; xu=4.25;
x(4)=bisection1(func,xl,xu);
x1(4)=fzero(func,[xl,xu]);
xl=4.25; xu=4.35;
x(5)=bisection1(func,xl,xu);
x1(5)=fzero(func,[xl,xu]);
xl=4.5; xu=5;
x(6)=bisection1(func,xl,xu);
x1(6)=fzero(func,[xl,xu]);
x
x1
func(x)
func(x1)
X=3:0.001:5;
plot(X,func(X))
hold on
plot(x,func(x),'o')
function root=bisection1(func,x1,xu)
xr=x1;es=.0001;
i=0;
while i<6
i=i+1;
xrold=xr;
xr=(x1+xu)/2;
if xr~=0
ea=abs((xr-xrold)/xr)*100;
root=xr;
else
ea=100;
root=xr;
end
if func(x1)*func(xr)<0
xu=xr;
root=xr;
elseif func(x1)*func(xr)>0
x1=xr;
root=xr;
else
ea=0;
root=xr;
end
if ea<=es,break,end
end
root=xr;
end
0 commentaires
Voir également
Catégories
En savoir plus sur Software Development Tools dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!