Search code examples
matlaboctave

Evaluating a recurring series in Octave using a while loop


I'm trying to evaluate the series ∑n=1 un in Octave, using a while loop. The recurrence relation un+1 = (un)2 is provided.

The summation should stop when |un| < 10-8.

So far this is what I got:

n=30
ser(1)=0.5;
sumser(1)=ser(1)
for k=1:n
    ser(k+1)=ser(1)^2;
end
for k=1:n
    while sumser(k)<10^-8
        sumser(k+1)=sumser(k)+ser(k+1)
    endwhile
end

I keep getting the error:

error: addex: A(I): index out of bounds; value 2 out of bound 1

error: called from

addex at line 8 column 3


Solution

  • If I've understood your problem correctly, then this should do the trick. There are too many problems with your code to address individually (unless I've misunderstood the question):

    u(1) = 0.5;
    S = u;
    n = 1;
    while (abs(u(n)) >= 10e-8)
        n = n + 1;
        u(n) = u(n-1)^2;
        S(n) = u(n) + S(n-1);
    end