correction for loop in bisection method

21 次查看(过去 30 天)
Hi all, I tried to work on bisection method. However, that is an error at the loop. I guess that there might be a problem with inline code at the loop. Please help me correct them. Thank you,
A=input('Enter A: ');
B=input('Enter B: ');
e=0;
func = inline('exp(x)-2cos(x)' , ' X');
while e<0.0001
for i=1:10
C=(A+B)/2
FC=func(C);
FB=func(B);
if(FC*FB>0)
B=C;
else
A=C;
end
e=(abs((FB-FC)/FB))*100
end
end

回答(2 个)

Mischa Kim
Mischa Kim 2015-6-17
编辑:Mischa Kim 2015-6-17
Anupan, check out
A = input('Enter A: ');
B = input('Enter B: ');
func = @(x) exp(x)-2*cos(x); % use instead anonymous functions
e = 1; % set e > 0.0001 to start search
while e>0.0001 % one loop is sufficient -> remove for loop
C = (A+B)/2;
FC = func(C);
FB = func(B);
if(FC*FB>0)
B = C;
else
A = C;
end
e = (abs((FB-FC)/FB))*100
end

Tamima  Nisat
Tamima Nisat 2022-1-10
f = @(x)(2*x^2-5*x+3)
xl=0;
xu=10;
error=0.001;
while(f(xl)*f(xu)>0)
xl=input('New input for lower ');
xu=input('New input for upper ');
end
while(abs(xu-xl)>error)
xc=(xu+xl)/2;
if(f(xl)*f(xc)<0)
xu=xc;
else
xl=xc;
end
end
fprintf('result=%f',xc)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by