Random number generator of normal distribution in C #

Source: Internet
Author: User
Tags datetime generator log
Random

Box and Muller in 1958 years, the algorithm for generating the random variable of normal distribution by the uniformly distributed random variable is given. Set U1, U2 is a uniformly distributed random variable on the interval (0, 1), and is independent of each other.


The main reference is "numerical Recipes in C + + 2/e" p.292~p.294 and "simulation Modeling and Analysis 3/e" p.465~p.466.

Box and Muller in 1958 years, the algorithm for generating the random variable of normal distribution by the uniformly distributed random variable is given. Set U1, U2 is a uniformly distributed random variable on the interval (0, 1), and is independent of each other. Make

X1 = sqrt ( -2*log (U1)) * cos (2*PI*U2);
X2 = sqrt ( -2*log (U1)) * sin (2*PI*U2);

Then X1, X2 obey N (0,1) distribution, and independent of each other. It means that we get two independent N (0,1) random numbers with two independent U (0,1) random numbers.

Marsaglia and Bray introduced an improved algorithm in 1964 to avoid trigonometric functions. This improved algorithm is used for the following implementation code.


//
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.