Search code examples
matlabif-statementwhile-loopconvergence

While Loops and Testing for Convergence


I have being trying to use a while loop to test convergence for X(n) = X(n-1)+((-1)^n)/n), as n tends towards infinity. I cannot seem to get my code to work. I know by definition Xn be a sequence and Xn has a limit if for all E>0 there exists K E N such that |Xn - L| < E. (I do apologies, I'm not sure how to insert greek letters in here). Initially I tried this and it didn't work and then though about instead of to find convergence with the L but to use the difference between two consequent elements: |X(n) - X(n-1) | < E for n -> infinity.

I'm not sure where I have gone wrong.

K=1;
x(K)=x(K-1)+((-1)^K)/K;
eps=0.0001;
L=0;
while abs(x(K)-x(K-1))>eps && K<10^5
K=K+1;
x(K+1)=x(K-1)+((-1)^K)/K;
end
sprintf('K is %d, x(K)=%f', [K, x(K)])
if abs(x(K)-x(K-1))< eps && K<10^5
% test that condition hold for any n>K 
n=fix(rand()*100)+K;
x_n=x(n-1)+((-1)^n)/n; %corresponds to x(n) 
    if abs(x_n-(x(n-1)+((-1)^n)/n))<eps
        sprintf(['the test did not fail\n',...
' The sequence satisfies the definition'])
    else
   sprintf('the test for convergence failed')
    end
else
  sprintf('The sequence did not converge over %d iterations', [K])
end  

Solution

  • Add the below two lines at the beginning to make your code to run,

    x(1)=1;
    K=2;
    

    then plot

    plot(abs(x))
    

    and you can see this is an oscillatory function and it won't converge.