gpt4 book ai didi

excel - Excel VBA 的 Rnd() 真的有这么糟糕吗?

转载 作者:行者123 更新时间:2023-12-02 21:46:04 25 4
gpt4 key购买 nike

我需要一个用于 2D 蒙特卡洛模拟的伪随机数生成器,它不具有通过简单 LCG 获得的特征超平面。我使用以下代码在 Excel 2013 中测试了随机数生成器 Rnd()(运行大约需要 5 秒):

Sub ZoomRNG()

Randomize
For i = 1 To 1000
Found = False
Do
x = Rnd() ' 2 random numbers between 0.0 and 1.0
y = Rnd()
If ((x > 0.5) And (x < 0.51)) Then
If ((y > 0.5) And (y < 0.51)) Then
' Write if both x & y in a narrow range
Cells(i, 1) = i
Cells(i, 2) = x
Cells(i, 3) = y
Found = True
End If
End If
Loop While (Not Found)
Next i

End Sub

这是运行上述代码时 x 与 y 的简单绘图

enter image description here

它不仅看起来不是很随机,而且比臭名昭著的 RANDU 算法在 2D 中具有更明显的超平面。基本上,我是否错误地使用了该函数,或者 VBA 中的 Rnd() 函数实际上一点也不可用?

为了进行比较,以下是我用 C++ 获得的 Mersenne Twister MT19937 的结果。

enter image description here

最佳答案

为了产生更好的随机生成器并使其性能更快,我修改了您的代码,如下所示:

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

我在绘制结果后得到这个

enter image description here

结果看起来比代码的输出更好。将上面的代码稍微修改一下,如下所示

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

产生比前一个更好的结果

enter image description here

当然,C++ 中的 Mersenne Twister MT19937 仍然更好,但最后的结果非常适合进行蒙特卡罗模拟。 FWIW,您可能有兴趣阅读这篇论文:On the accuracy of statistical procedures in Microsoft Excel 2010 .

关于excel - Excel VBA 的 Rnd() 真的有这么糟糕吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38891165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com