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 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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.
Respuestas (1)
Walter Roberson
el 2 de Oct. de 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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!