Also, it didn't do the infinite loop when I did not have error=abs(((x(n+1))-(x(n))) before the loop, and just, abs(((x(n+1))-(x(n)))>tol as the while loop.
How do I stop the infinite loop in this fixed point iteration code?
조회 수: 7 (최근 30일)
이전 댓글 표시
Here is my code:
%fixedpoint
g=@(x) 1-(1/7).*exp(1).^x;
n=1;
x(1)=0.5;
x(2)=g(x(1));
tol = (0.5*10e-10);
error = abs((x(n+1))-(x(n)));
while error>tol
n=n+1;
x(n+1)=g(x(n));
end
format long
disp(x(n))
disp(n)
semilogy()
I cannot figure out how to stop the infinite loop I've tried cVals, and allowing for the max iterations (which I could have been wrong in the code I put in). Also, Im not sure what goes in semilogy() to plot the error as a function of n on the same set of axes. Any help would be greatly appreciated, thank you.
답변 (1개)
Walter Roberson
2015년 10월 2일
Your code has
while error>tol
n=n+1;
x(n+1)=g(x(n));
end
You do not change the variable "error" inside the loop, so if the loop is ever entered at all, there is no way out of the loop. You need to change "error" inside the loop.
Note: it is not a good idea to use "error" as the name of a variable, as that interferes with the use of the important MATLAB routine named "error"
댓글 수: 2
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!