Normal Distribution of random number generator in C #

Source: Internet
Author: User

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;
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.