При имитации бросков костей с помощью функции Rnd
я заметил, что некоторые результаты были более частыми, чем предполагалось.
Пример кода:
' Note, depending on computer speed this procedure may take about a minute to run
Sub sim3()
Dim intFirst As Integer, intSecond As Integer, intDie1 As Integer, intDie2 As Integer
Dim i As Long, j As Long, lngCount As Long, lngExpected As Long, lngLowerCount As Long, lngIterations As Long
lngIterations = 1000000
' select dice roll
intDie1 = 1 ' any number between 1 and 6
intDie2 = 3 ' any number between 1 and 6
' expected frequency
' (= 55,555 if lngIterations = 1,000,000 and intDie1 <> intDie2, = 27777 if lngIterations = 1,000,000 and intDie1 = intDie2)
If intDie1 = intDie2 Then lngExpected = Int((1 / 36) * CDbl(lngIterations)) Else _
lngExpected = Int((2 / 36) * CDbl(lngIterations))
For i = 1 To 100
lngCount = 0
For j = 1 To lngIterations
If j Mod 10000 = 0 Then DoEvents ' outcomment for faster execution
intFirst = randomDie
intSecond = randomDie
' count occurences of specific outcomes
If intFirst = intDie1 And intSecond = intDie2 Then ' 1,4
lngCount = lngCount + 1
ElseIf intFirst = intDie2 And intSecond = intDie1 Then ' 4, 1
lngCount = lngCount + 1
End If
Next j
If lngCount < lngExpected Then lngLowerCount = lngLowerCount + 1
Debug.Print i & ": #favourable outcomes: " & lngCount ' outcomment for faster execution
Next i
Debug.Print "(" & intDie1 & "," & intDie2 & ") #expected favourable outcomes per iteration (int.): " & lngExpected
Debug.Print "(" & intDie1 & "," & intDie2 & ") #iterations with lower than expected number of favourable outcomes: " & lngLowerCount
Debug.Print "(" & intDie1 & "," & intDie2 & ") Prob. of obtaining result or lower, F(x|n,p) : " & WorksheetFunction.Binom_Dist(lngLowerCount, i, 0.5, True)
End Sub
The randomDie
функция, используемая в процедуре, представляет собой стандартный код для генерации целого числа от 1 до 6 ( источник ):
Function randomDie() As Integer
Randomize
randomDie = Int((6 * Rnd) + 1)
End Function
Обратите внимание на оператор Randomize
, который сдвигает начальное число PRNG VBA алгоритм каждый раз, когда функция вызывается, что означает, что результаты процедуры sim3
будут не одинаковыми каждый раз, когда она выполняется.
Результаты для 21 комбинации кубиков бросаются вместе с вероятность получения этого или более низкого результата:
введите описание изображения здесь
Мы ожидаем, что результаты благоприятных исходов будут примерно равномерно распределены вокруг среднего (μ = 50, i=100
), но эти результаты абсолютно экстремальные .
Есть ли в моем коде fl aws, проблема в моем компьютере или VBA PRNG смещен?