VBA中的递归代码 [英] Recursion code in VBA
问题描述
我正在尝试运行此代码以计算附图中公式 16.4 中不同 Tn 下的 Q(n).但它没有给我正确的输出.我将不胜感激任何帮助.注意:delta1=delta2 =...deltan = dt=1(我在这里取过)并进一步将 S 项除以 10000,因为在等式中它处于基点,即 1% 的第 100 部分.
I am trying to run this code to calculate Q(n) at different Tn in the Equation 16.4 in the attached picture.But its not giving me the correct output. I would appreciate any help. Note: delta1=delta2 =...deltan = dt=1 ( I have taken here ) and further divided S term by 10000 just because in the Equation it is in basis point i.e. 100th part of 1 %.
Function Bootstrap(S As Range, Z As Range, L As Double) As Double
Dim j As Integer
Dim a As Variant
Dim b As Variant
Dim n As Integer
Dim Q() As Double
Dim sum As Double
Dim P As Double
Dim dt As Double
n = Application.WorksheetFunction.Max(S.Columns.Count, Z.Columns.Count)
a = S.Value
b = Z.Value
dt = 1
sum = 0
ReDim Q(0 To n)
Q(0) = 1
For j = 1 To n - 1
P = (b(1, j) * (L * Q(j - 1) - (L + dt * a(1, n) / 10000) * Q(j))) / (b(1, n) * (L + a(1, n) * dt / 10000)) + Q(n - 1) * L / (L + a(1, n) * dt / 10000)
sum = sum + P
Q(n) = sum
Next j
Bootstrap = sum
End Function
推荐答案
要解决递归函数,你可以这样写,例如
To solve a recursive function you can write it this way, for example
Function Factorial(n as long) as long
If n = 1 Then
Factorial = 1
Else
Factorial = n * Factorial(n-1)
End If
End function
是的,您可以看到 For...Loop
也可以进行因子计算,但在您的情况下,使用递归解决方案更容易.
Yes, you can see For...Loop
can also do the Factorial calculation, but in your case, its much easier to use recursive solution.
此外,等式 16.4 被有意编写为递归函数.它没有写成求和函数,因为这样做更难.如果给你的是求和函数,那么你可以应用 For...Loop
解决方案.
Besides Eq 16.4 is intentionally written as a recursive function. It is not written as a summation function because it is harder to do so. If given to you is a summation function, then you can apply the For...Loop
solution.
希望这会有所帮助.
编辑
Function Q(n as long) as double
If n = 1 Then
Q = 5
Else
Q = Z * ( L * Q_t - (L + d * S) * Q(n-1) ) / ( Z * ( L + d * S ) )
End If
End Function
注意函数Q
在n>1
时会在Q(n-1)
中不断调用自己.这就是所谓的递归解决方案.
Notice that the function Q
keep calling itself in Q(n-1)
when n>1
. That is called recursive solution.
(检查公式.我可能抄错了)
(Check the formula. I might copy it wrong)
这篇关于VBA中的递归代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!