My goal is to find how many times the iteration takes to have a tolerance of 10^-5 where g(x)=x

Here is my code... it will only run through once, and I dont know where I am going wrong...
g=@(x)(sin(x)^2 + 11/10);
x0=1;
x1=10;
TOL= 10^(-5);
N=0;
while abs(x1-x0)>TOL
x1=g(x0)
x0=x1;
N=N+1
end
I have more while loops that are doing the same thing (only running through once)... I think its in my abs() statement, but I don't know how to fix it...
I am trying to get it to run this
x0
x1=f(x0)
x2=f(x1)
x3=f(x2)
... until abs(xn-f(xn-1))<10^(-5)
Thank you!!

回答 (1 件)

Matt Fig
Matt Fig 2012 年 9 月 26 日
編集済み: Matt Fig 2012 年 9 月 26 日
You need to switch the order of assignment of x0 and x1 inside the loop. You first define x1, then say x0=x1. So the difference between them is of course 0, which is not greater than TOL! Rather, capture the old value of x1 in x0 first, then get the new value of x1 to compare...
g=@(x)(sin(x)^2 + 11/10);
x0=1;
x1=10;
TOL= 10^(-5);
N=0;
while abs(x1-x0)>TOL
x0=x1;
x1=g(x0);
N=N+1;
end
[N x1]

2 件のコメント

Bcsper
Bcsper 2012 年 9 月 26 日
I just did that!! Thank you!!!! Duh! lol
Jan
Jan 2012 年 9 月 26 日
編集済み: Jan 2012 年 9 月 26 日
Please accept this answer, if it solves your problem.
A marginal suggestion: "1.1" is faster than "11/10" as "1e-5" is faster than "10^(-5)". While this saves some microseconds in your case, it could be important in larger programs.

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

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

質問済み:

2012 年 9 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by