2016-12-02 85 views
0

離開我有以下一塊代碼使用隨機過程VBA:For循環,而不返回值

Function varswap1(s0, r0, sigma0, t) As Double 
    Rnd (-10) 
    Randomize (999) 

Dim i As Integer, j As Integer, r As Double 
Dim stock() As Double, dt As Double 
Dim per As Integer 
    per = WorksheetFunction.Round(t * 252, 0) 

    ReDim stock(per) 
    stock(1) = s0 
    dt = 1/252 

    For i = 1 To per 
    stock(i + 1) = stock(i) * Exp((r0 - 0.5 * sigma0^2) * dt + sigma0 * Sqr(dt) * WorksheetFunction.NormSInv(Rnd())) 
    Next 

    varswap1 = WorksheetFunction.Average(stock) 
End Function 

在該代碼模擬股票價格,我通過放置一個斷點在接下來和整個運行調試For循環工作得很好。問題是在完成循環之後,函數退出,並且單元格中顯示#VALUE!錯誤。

我無法弄清楚這段代碼有什麼問題。 如果有人能幫助我,我將非常感激。

+3

倒數第二次循環迭代在試圖評估'stock(i + 1)'時應該給出一個下標錯誤,因爲'stock'只有'per''元素(並且基於零)。 – Comintern

+0

Think @Comintern已經釘住了它 - 同時'Average()'將只接受最多255個值來計算。 –

+0

好的。非常感謝。 – Chinmay

回答

0

試試這個:

Const n As Integer = 252 

Function varswap1(s0, r0, sigma0, t) As Double 
    Rnd (-10) 
    Randomize (999) 

Dim i As Integer, j As Integer, r As Double 
Dim stock() As Double, dt As Double 
Dim per As Integer 
    per = WorksheetFunction.Round(t * n, 0) 

    ReDim stock(per) 
    stock(0) = s0 ' First item in the array has index 0 
    dt = 1#/n ' Avoid integer division, 1/252 = 0 

    For i = 1 To per 
    'Each stock depends on the previous stock value: 
    stock(i) = stock(i - 1) * Exp((r0 - 0.5 * sigma0^2) * dt + sigma0 * Sqr(dt) * WorksheetFunction.NormSInv(Rnd())) 
    Next 

    varswap1 = WorksheetFunction.Average(stock) 
End Function 

我看到了兩個問題,一個建議。

其中一個是數組stock0..252開始,但是您將值分配給1..253以致它崩潰。

此外還有一個可能的整數除法導致dt=0.0。我更新了定義以明確說明在從整數轉換爲雙精度之後完成除法。最後,我將魔法數字252移至常量。