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?
3 次查看(过去 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!