Is Excel VBA's Rnd() really this bad?

前端 未结 5 952
情深已故
情深已故 2020-12-10 03:59

I need a pseudo random number generator for 2D Monte Carlo simulation that doesn\'t have the characteristic hyperplanes that you get with simple LCGs. I tested the random nu

5条回答
  •  一生所求
    2020-12-10 04:07

    To yield a better random generator and to make its performance faster, I modified your code like this:

    Const N = 1000           'Put this on top of your code module
    Sub ZoomRNG()
    
    Dim RandXY(1 To N, 1 To 3) As Single, i As Single, x As Single, y As Single
    
    For i = 1 To N
        Randomize            'Put this in the loop to generate a better random numbers
        Do
            x = Rnd
            y = Rnd
            If x > 0.5 And x < 0.51 Then
                If y > 0.5 And y < 0.51 Then
                    RandXY(i, 1) = i
                    RandXY(i, 2) = x
                    RandXY(i, 3) = y
                    Exit Do
                End If
            End If
        Loop
    Next
    Cells(1, 9).Resize(N, 3) = RandXY
    End Sub
    

    I obtain this after plotting the result

    The result looks better than your code's output. Modifying the above code a little bit to something like this

    Const N = 1000
    Sub ZoomRNG()
    
    Dim RandXY(1 To N, 1 To 3) As Single, i As Single, x As Single, y As Single
    
    For i = 1 To N
        Randomize
        Do
            x = Rnd
            If x > 0.5 And x < 0.51 Then
                y = Rnd
                If y > 0.5 And y < 0.51 Then
                    RandXY(i, 1) = i
                    RandXY(i, 2) = x
                    RandXY(i, 3) = y
                    Exit Do
                End If
            End If
        Loop
    Next
    Cells(1, 9).Resize(N, 3) = RandXY
    End Sub
    

    yields a better result than the previous one

    Sure the Mersenne Twister MT19937 in C++ is still better, but the last result is quite good for conducting Monte-Carlo simulations. FWIW, you might be interested in reading this paper: On the accuracy of statistical procedures in Microsoft Excel 2010.

提交回复
热议问题