matlabrecursionoctave

recursive sqrt(2) ratio function in matlab / octave


I'm trying to create a recursive sqrt(2) ratio function in matlab / octave. I can create the recursive pattern in a spreadsheet see numbers and the corresponding formulas that create them below.

Recursive numbers

Recursive formulas

I'm having trouble getting the function to work correctly in matlab / octave. The a and b values should match the spreadsheet images above.

function f = rtsqrt2(a,b,n)          
  for rr=1:n
    rr
    if (rr==1)
      ab_num(rr,:)=[a,b];

    elseif (rr==2)
      a=a+b+b;
      b=1+b;
      ab_num(rr,:)=[a,b];

    elseif 
      a=a+b+b;
      b=a+b;
      ab_num(rr,:)=[a,b];

    end
  end
  ab_num
end

when I do a rtsqrt2(1,1,10) Error

The first two lines are correct but on the third line I get 7,9 instead of what I should get 7,5 and things get worse from there. How can I fix it so that my recursive function follows the pattern in the first image.

Please note I'm using octave 4 which is similar to matlab and that I plan on using more than just 10 recursions (10 recursions were used just to test with)


Solution


Here's an implementation that fits your description. Note the computation (as you described) is iterative not recursive.

I've included some extra bits in the function to make and display the table.

function x = rtsqrt2(a, b, n)
%% Compute the square root of 2 iteratively
%
% n = number of iterations
% a, b  are the initial values

%Initialise the vector A and B to hold the computation for each step
A = zeros(1, n);
A(1) = a;
B = zeros(1, n);
B(1) = b;
C = zeros(1, n);

% Compute the values of A and B iteratively
for k = 2 : n
    A(k) = A(k-1) + 2 * B(k-1);
    B(k) = A(k-1) + B(k-1);
end

% Compute the entire C vector (a/b) in a vectorised manner
C = A ./ B;
% Create a table to display the table like you'd see in excel
TBL = table(A', B', C');
TBL.Properties.VariableNames = {'A' 'B' 'C'};
disp(TBL)

% sqrt(2)
x = C(end);

Here's the function running:

>>> rtsqrt2(1, 1, 10)
 A       B        C   
____    ____    ______

   1       1         1
   3       2       1.5
   7       5       1.4
  17      12    1.4167
  41      29    1.4138
  99      70    1.4143
 239     169    1.4142
 577     408    1.4142
1393     985    1.4142
3363    2378    1.4142


ans =

1.4142