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

I just did that!! Thank you!!!! Duh! lol
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.

댓글을 달려면 로그인하십시오.

태그

질문:

2012년 9월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by