首页 > 解决方案 > 在 Excel VBA 中有效地生成快速正态分布的随机数

问题描述

我一直在寻找一种快速可靠的方法来生成正态分布的随机数。

最流行的方法似乎是使用 Excel 工作表函数 Norm_Inv 和一个随机数,但这很慢,因为需要在 Excel 和 VBA 之间来回切换。

我在下面分享我的解决方案,但如果有更好的解决方案,我很想知道。

标签: excelvbarandomnormal-distribution

解决方案


该解决方案非常快速且准确,可满足您的需要。最初,您将区间 0-1 划分为大量切片并调用 NORM_INV 以获取每个点的正态分布值,并将这些值存储在一个数组中。之后,您无需再调用 NORM_INV,只需查找任意随机数的数组值即可。

1000 个切片似乎足以与直接使用 NORM_INV 提供 99% 以上的相关性。

Function NormalRandLookup(Optional Mean As Single = 0, Optional StdDev As Single = 1) As Single
  Static R() As Single, n As Long 
  If n = 0 Then 'set up the lookup table initially
    Dim i As Long
    n = 1000 'vary this to reduce or increase accuracy 
    ReDim R(0 To n)
    R(0) = -3.3: R(n) = 3.3 'the extreme values returned by NORM_INV for 0 and 1
    For i = 1 To n - 1 
      R(i) = Application.WorksheetFunction.Norm_Inv(i / n, 0, 1)
    Next i
  End If
  NormalRandLookup = Mean + StdDev * R(Rnd * n)
End Function

推荐阅读