【Excel VBA】乱数生成【二項分布, ポワソン分布, 正規分布, t分布, 対数正規分布, 指数分布, 一様分布】
二項分布の乱数生成
二項分布は、成功確率 p の試行を n 回繰り返したときの成功回数を表します。VBAで二項分布の乱数を生成するには、乱数を使って成功回数をカウントします。
Function BinomialRnd(n As Integer, p As Double) As Integer
Dim i As Integer, count As Integer
count = 0
For i = 1 To n
If Rnd() < p Then count = count + 1
Next i
BinomialRnd = count
End Function
ポワソン分布の乱数生成
ポワソン分布は、一定時間内のランダムなイベントの発生回数をモデル化します。平均 λ に従うポワソン乱数を生成するには指数関数を利用します。
Function PoissonRnd(lambda As Double) As Integer
Dim L As Double, p As Double, k As Integer
L = Exp(-lambda)
k = 0
p = 1
Do
k = k + 1
p = p * Rnd()
Loop While p > L
PoissonRnd = k - 1
End Function
正規分布の乱数生成
正規分布の乱数を生成するには、Box-Muller変換を利用します。
Function NormalRnd(mu As Double, sigma As Double) As Double
Dim u1 As Double, u2 As Double
u1 = Rnd()
u2 = Rnd()
NormalRnd = mu + sigma * Sqr(-2 * Log(u1)) * Cos(2 * 3.14159265358979 * u2)
End Function
t分布の乱数生成
t分布の乱数は、正規分布の乱数とカイ二乗分布を用いて生成します。
Function TRnd(df As Integer) As Double
Dim norm As Double, chi2 As Double
norm = NormalRnd(0, 1)
chi2 = 0
Dim i As Integer
For i = 1 To df
chi2 = chi2 + (NormalRnd(0, 1) ^ 2)
Next i
TRnd = norm / Sqr(chi2 / df)
End Function
対数正規分布の乱数生成
対数正規分布は、正規分布の指数関数として生成できます。
Function LogNormalRnd(mu As Double, sigma As Double) As Double
LogNormalRnd = Exp(NormalRnd(mu, sigma))
End Function
指数分布の乱数生成
指数分布はポアソン分布の待ち時間モデルとして使われます。
Function ExponentialRnd(lambda As Double) As Double
ExponentialRnd = -Log(Rnd()) / lambda
End Function
一様分布の乱数生成
VBAのRnd関数は [0,1) の一様分布に従う乱数を生成します。範囲を調整するには次のようにします。
Function UniformRnd(a As Double, b As Double) As Double
UniformRnd = a + (b - a) * Rnd()
End Function