matlab / octave中的递归sqrt(2)比率函数

recursive sqrt(2) ratio function in matlab / octave

我正在尝试在 matlab/octave 中创建递归 sqrt(2) 比率函数。 我可以在电子表格中创建递归模式,请参阅下面的数字和创建它们的相应公式。

我无法让函数在 matlab/octave 中正常工作。 ab 值应与上面的电子表格图像匹配。

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

当我做 rtsqrt2(1,1,10)

前两行正确,但在第三行 我得到 7,9 而不是我应该得到的 7,5 并且事情从那里变得更糟。我该如何修复它,以便我的递归函数遵循第一张图片中的模式。

请注意,我使用的是与 matlab 类似的 Octave 4,并且我计划使用超过 10 个递归(10 个递归仅用于测试)

这是一个符合您的描述的实现。请注意计算(如您所述)是迭代的​​而不是递归的。

我在函数中添加了一些额外的位来制作和显示 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);

这是函数 运行:

>>> 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

为了让它在 Octave 4.0 中工作,这里有一些小的调整

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;
x=[A;B;C]';
%% 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);

end