簡體   English   中英

在MATLAB中編寫遞歸

[英]Coding a recursion in MATLAB

我一直試圖嘗試編寫一個MATLAB算法來反向計算遞歸,或者這對我來說似乎就是卡住了。 y_n =(1 / n)−10 * y_n−1,其中n = 1,...,30在MATLAB中有效,但是由於(* 10),舍入誤差使算法不穩定,並且沒有用。 僅通過操縱遞歸,y_n-1 =(1/10)(1 / n-y_n)就可以工作,並且舍入誤差將在每個步驟中減少10倍,這可能使它成為一種穩定的算法。

幾天后,我仍然無法理解編寫此代碼所需的邏輯。 評估y_n-1確實使我陷入循環。 我能夠解決不穩定的算法,但是我想不出處理代碼以使其正常工作的邏輯。 我的問題在於如何在MATLAB中編寫代碼? 我真的很沮喪。

% Evaluate the integral yn = integral from 0 to 1 of x^n/(x+10).
% Unstable algorithm:
y(1) = log(11) - log(10);
k = 30;
for n = 1:k
    y(n+1) = (1/n) - 10*y(n);
end
n_vector = 0:k;
[n_vector;y] 

通過操縱遞歸,由於誤差的限制,結果將接近真實值。 當前輸出:

0.0953101798043248 
0.0468982019567523 
0.0310179804324768 
0.0231535290085650 
0.0184647099143501 
0.0153529008564988 
0.0131376581016785 
0.0114805618403582 
0.0101943815964183 
0.00916729514692832 
0.00832704853071678 
0.00763860560192312 
0.00694727731410218 
0.00745030378205516 
-0.00307446639198020 
0.0974113305864686 
-0.911613305864686 
9.17495658805863 
-91.6940103250307 
916.992734829255 
-9169.87734829255 
91698.8211019731 
-916988.165565185 
9169881.69913012 
-91698816.9496345 
916988169.536345 
-9169881695.32499 
91698816953.2869 
-916988169532.833 
9169881695328.37 
-91698816953283.7

在考慮了舍入誤差的情況下,預期結果將保持在01之間。

您得到的輸出是正確的,並且正如Mad Physicist的評論所指出的那樣,您具有的遞歸函數應該以這種方式運行。

如果查看兩個項的行為,則隨着n變大,初始減法將對10 * y(n)項的影響較小。 因此,對於大n,我們可以忽略1 / n。

然后,在n大的情況下,我們期望每個步驟將使我們的價值增加大約10倍。這就是您在輸出中看到的。

至於寫一個向后遞歸。 根據定義,您需要一個起始值,因此您需要假設y(30)並按照注釋中的建議向后運行遞歸。

因此,我能夠通過自己的問題回答。 所需的代碼如下所示:

% This function calculates the value of y20 with a guarantee to have an 
% absolute error less than 10^-5
% The yn1 chosen to be high enough to guarantee this is n1 = 25
% Returns the value of y(20)

function [x]= formula(k)

% RECURSION APPROXIMATION
y(k) = 0;
n = k:-1:20;
y(n-1) = (1./10)*(1./n - y(n));
x = y(20);
% FURTHER:  I needed to guarantee y20 to have <= 10^-5 magnitude error
% I determined n=25 would be my starting point, approximating y25=0 and working
% backwards to n=20 as I did above.

%  y(n-1)=1/10(1/n-yn)    “exact solution”
%  (yn-1)*=1/10(1/n-(yn)*)    “approximate solution with error”
%  y(n-1)-(y(n-1))*=1/10(1/n-yn)-1/10(1/n-(yn)*)   calculating the error
%              = 1/10((yn)*-yn)
%  So,
%  E(n-1)=1/10(En)
%  E(n-2)=1/100(E(n-1))
%  E(n-3)=1/1000(E(n-2))
%  E(n-4)=1/10000(E(n-3))
%  E(n-5)=1/100000(E(n-4)) ⇒ 10^(-5)
%  En20=(10^-5)En25
%  Therefore, if we start with n1=25, it guarantees that y20 will have 10^-5 magnitude of % the initial propagating error.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM