2012-07-12

Normal distribution from uniform random in VBscript

Because everyone needs to generate a normally distributed random number set at least once in their life, right? Why not do it in the programming language that comes with nearly every version windows since Microsoft started ripping off Apple.
' * Static *
Dim NormalRandToggle, NormalRandTemp

Function NormalRand(ByVal thisMean, ByVal thisStandardDev)
' Outputs Gaussian/Normal distributed random numbers using Box-Muller algorithm.
' Note the function creates two at a time,
' so global variables are used to store and output the second number on demand
If NormalRandToggle = 1 Then
 NormalRandToggle = 0
 NormalRand = NormalRandTemp
Else
 NormalRandToggle = 1
 Dim R1, R2, rad, t
 Do Until rad > 0.0 AND rad < 1.0
  R1 = (2.0 * Rnd()) - 1.0
  R2 = (2.0 * Rnd()) - 1.0
  rad = R1^ 2 + R2^2
 Loop
 t = Sqr(-2.0 * Log(rad) / rad)
 NormalRandTemp = t * R2 * thisStandardDev + thisMean
 NormalRand = t * R1 * thisStandardDev + thisMean
End If
End Function



' *** TEST ***

Randomize
Dim i, R, N, S, SS, M, V, SD
N = 0
S = 0
SS = 0
For i = 1 To 1000000
 N = N + 1
 R = NormalRand (100, 33)
 S = S + R
 SS = SS + R^2
Next
M = S / N
V = SS / N - M ^ 2
SD = Sqr(V)
WScript.Echo "Mean = " & M & " Var = " & V & " StdDev = " & SD
Thanks to Zaza for example VB code and Peter Kankowski for the one pass variance/standard deviation calculation in the test.