Infinite loop in False postion method

조회 수: 3 (최근 30일)
R Abhinandan
R Abhinandan 2020년 10월 27일
댓글: Cris LaPierre 2020년 10월 27일
Here is my code for false position method and im getting a infinite loop, i want it to stop at tol=10^-4, can someone help?
a=0.5;
b=1;
tol=0.0001;
counter=0;
f =@(x) exp(x)-3*x^2;
while abs(b-a)>tol
c= b - (f(b)* (b-a)/(f(b)-f(a)));
if f(a)*f(c)<0
b=c;
end
if f(a)*f(c)>0
a=c;
end
counter=counter+1;
er=abs(a-b);
errorcounter(counter)=er;
end
figure
hold on
plot(errorcounter)
title('Convergence of False Position')
ylabel('Error')
xlabel('Iterations')
axis ([0 5 0 9e-04])
  댓글 수: 1
Cris LaPierre
Cris LaPierre 2020년 10월 27일
btw, hold on is unnecessary here. When used, it should always be paired with hold off.

댓글을 달려면 로그인하십시오.

채택된 답변

Cris LaPierre
Cris LaPierre 2020년 10월 27일
I don't understand what your approach is, but by converting your while loop to a for loop, I can see that your error stops decreasing at 0.09. Here's a simplified version of your code.
a=0.5;
b=1;
f =@(x) exp(x)-3*x^2;
% while abs(b-a)>tol
for loop = 1:10
c= b - (f(b)* (b-a)/(f(b)-f(a)));
if f(a)*f(c)<0
b=c;
elseif f(a)*f(c)>0
a=c;
end
er=abs(a-b)
end
er = 0.1193
er = 0.0915
er = 0.0901
er = 0.0900
er = 0.0900
er = 0.0900
er = 0.0900
er = 0.0900
er = 0.0900
er = 0.0900
  댓글 수: 2
R Abhinandan
R Abhinandan 2020년 10월 27일
I want the loop to stop at tol=10^-4, for example here is my code for bisection method which works perfectly but when i tried for false postion it doesn't
f=@(x) exp(x)-3*(x)^2;
a=0.5;
b=1;
tol=10^(-4);
counter = 0;
while abs(b-a) > tol
c = (b+a)/2;
if (f(a)*f(c)) <0
b = c;
end
if (f(a)*f(c)) >0
a = c;
end
counter = counter + 1;
err(counter) = abs(a - b);
end
disp(b)
figure
hold on
plot(err)
title('Convergence of Bisection')
ylabel('Error')
xlabel('Iterations')
axis ([0 13 0 0.0001])
Cris LaPierre
Cris LaPierre 2020년 10월 27일
편집: Cris LaPierre 2020년 10월 27일
I understand. Check your algorithm. You have not implemented it correctly.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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