Monte Carlo Simulation in VBA consistently underestimates the true value

前端 未结 1 1679
小鲜肉
小鲜肉 2021-01-23 11:48

I have a weird problem with a Monte Carlo Simulation that I built. It is a nested loop to calculate the expected value of investments (actually Poker Tournaments). To demonstrat

相关标签:
1条回答
  • 2021-01-23 12:03

    It looks like you are repeatedly calling Randomize, presumably as part of a tight loop. Every time this is called, it reseeds the random number generator from the system clock. Doing so with each pass through the loop introduces autocorrelations (though exactly how isn't quite clear).

    Consider the following experiment:

    Sub Test()
        Dim i As Long, A As Variant
        Dim count1 As Long, count2 As Long
        ReDim A(1 To 10000)
    
        For i = 1 To 10000
            Randomize
            A(i) = IIf(Rnd() < 0.5, 0, 1)
        Next i
    
        'count how often A(i) = A(i+1)
        For i = 1 To 9999
            If A(i) = A(i + 1) Then count1 = count1 + 1
        Next i
    
        For i = 1 To 10000
            A(i) = IIf(Rnd() < 0.5, 0, 1)
        Next i
    
        'count how often A(i) = A(i+1)
        For i = 1 To 9999
            If A(i) = A(i + 1) Then count2 = count2 + 1
        Next i
    
       Debug.Print "First Loop: " & count1
       Debug.Print "Second Loop: " & count2 & vbCrLf
    
    End Sub
    

    Typical output:

    First Loop: 5452
    Second Loop: 4996
    

    I have run it several times. The first loop almost always produces a number which differs from 5000 by a large amount whereas the second loop almost always produces a number fairly close to 5000 (the expected value is 4999.5 if successive calls to Rnd correspond to independent random variables -- hence there is a distinct lack of independence when repeatedly reseeding).

    Moral of the story: call Randomize just once in the simulation, say as the first line of the main sub. Alternatively, use Application.WorksheetFunction.RandBetween(0,1) and let Excel worry about the seeding.

    If this autocorrelation doesn't explain the error, the problem lies in the code that you haven't shown, so you would need to include that code.

    0 讨论(0)
提交回复
热议问题