For more information, see numerical recipes in C ++ 2/e p.292 ~ P.294 and Simulation Modeling and Analysis 3/e p.465 ~ P.466.
Box and Muller provided an algorithm for generating a normally distributed random variable from a uniformly distributed random variable in 1958. Where U1 and U2 are random variables with a uniform distribution on the intervals (0, 1), they are independent of each other. Ling
X1 = SQRT (-2 * log (U1) * Cos (2 * pI * U2 );
X2 = SQRT (-2 * log (U1) * sin (2 * pI * U2 );
Therefore, X1 and X2 are subject to the N () distribution and are independent of each other. We use two independent random numbers U (0, 1) to obtain two independent random numbers N (0, 1.
Marsaglia and Bray proposed an improved algorithm in 1964 to avoid using trigonometric functions. The following implementation code uses this improved algorithm.
//
// Gaussian random number generator class
// Ref. ''numerical recipes in C ++ 2/e'', p.293 ~ P.294
//
Public class gaussianrng
{
Int Iset;
Double gset;
Random R1, R2;
Public gaussianrng ()
{
R1 = new random (unchecked (INT) datetime. Now. ticks ));
R2 = new random (~ Unchecked (INT) datetime. Now. ticks ));
Iset = 0;
}
Public double next ()
{
Double FAC, rsq, V1, V2;
If (Iset = 0 ){
Do {
V1 = 2.0 * r1.nextdouble ()-1.0;
V2 = 2.0 * r2.nextdouble ()-1.0;
Rsq = V1 * V1 + V2 * V2;
} While (rsq> = 1.0 | rsq = 0.0 );
FAC = math. SQRT (-2.0 * Math. Log (rsq)/rsq );
Gset = V1 * FAC;
Iset = 1;
Return V2 * FAC;
} Else {
Iset = 0;
Return gset;
}
}
}