How do I stop the infinite loop in this fixed point iteration code?

8 ビュー (過去 30 日間)
Sarah Harvey
Sarah Harvey 2015 年 10 月 2 日
コメント済み: Walter Roberson 2015 年 10 月 2 日
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 件のコメント
Sarah Harvey
Sarah Harvey 2015 年 10 月 2 日
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.

サインインしてコメントする。

回答 (1 件)

Walter Roberson
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 件のコメント
Sarah Harvey
Sarah Harvey 2015 年 10 月 2 日
Thank you so much! Also, do you know about the semilogy problem?
Walter Roberson
Walter Roberson 2015 年 10 月 2 日
You would record the error at each step and semilogy() that.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by