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 Kommentare

David Hill
David Hill am 31 Aug. 2022
Show us your code.
Angelina Encinias
Angelina Encinias am 31 Aug. 2022
Just did.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Torsten
Torsten am 31 Aug. 2022

0 Stimmen

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
x = 1×6
3.260937500000000 3.367187500000000 3.746875000000000 4.229687499999999 4.264062500000000 4.710937500000000
x1
x1 = 1×6
3.262423140266324 3.365992128846206 3.745745086972446 4.229067033678568 4.263590029871862 4.712388980384690
func(x)
ans = 1×6
-0.006942296312261 -0.005267769874115 0.014275699455641 -0.000954862685705 0.000745839854238 0.018868721583465
func(x1)
ans = 1×6
1.0e-14 * -0.122124532708767 0.166533453693773 0.333066907387547 -0.044408920985006 0.055511151231258 0.594077493713784
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

Kategorien

Mehr zu Debugging and Analysis finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2021b

Gefragt:

am 31 Aug. 2022

Bearbeitet:

am 31 Aug. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by