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 views (last 30 days)
Show older comments
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.
Answers (1)
Walter Roberson
on 2 Oct 2015
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!