'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 1:[1]

Analyzing the question leads to an expression of the maximal index n complying with the condition |u_n| >= Min with

u_0 = 0.5
Min = 1e-8
n_max = log(log(Min)/log(u_0))/log(2)

Then we have directly, without any slow while loop

Sum = sum(u_0^(2^(0:n_max)))

yielding

>> Sum = sum(u_0^(2^(0:n_max)))  
Sum  = 
   0.8164215

Solution 2:[2]

Actually you don't need to loop over n, but just vectorize your code. What you try to do is to sum a sequence until the element is smaller than a given tolerance (denoted as tol, and in this case is 10e-8). I assume that you would start with u(1)>0. Then, as long as u(1)<1 the process will eventually stop. Due to the recurrence relation, once u(1) and tol are pre-specified, we already know when to stop--when the u(n)>=tol but u(n+1)<=tol.Here is the code:

function s=sum_seq(u1,tol)
%tol is the tolerance. In your case, 10e-8
if(u1<0)||(u1>=1)
    disp('Error! Wrong choice of u(1)!');
    s=[];
else
    K=log10(tol)/log10(u1); %K=log_{u1}(tol) is an auxiliary variable
    n=floor(log2(K))+1; %It makes sure u(n)=u(1)^(2^(n-1))>tol>=u(n+1)
    A=u1.^(2^(0:n-1));
    s=sum(A);
end

Then, you call get your result by running s=sum_seq(0.5,10e-8). If you prefer not to use a function, then the four lines within the "else" part do the job. Hope that helps.

Solution 3:[3]

Another easier and intuitive way to solve this problem is to first get all the elements that will be in that series and then use the built in sum function to sum all of them up.

ser(1) = 0.5;
sumser = 0;
n = 1;

while(abs(ser(n)) >= 10e-8)

 ser(n+1) = ser(n)^2;
 n = n+1;
end

sumser = sum(ser)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 API
Solution 3 themba alex khumalo