Normal Distribution Random Number

Hi,
Can anyone tell me how to generate random numbers that are Normal Distribution (Guassian)?
Thanks
[120 byte] By [Godeyes01] at [2007-11-18 17:41:38]
# 1 Re: Normal Distribution Random Number
Red this FAQ ( http://www.dev-archive.com/forum/showthread.php?s=&threadid=284877). The book mentioned in the last paragraph has a very good description on how to do what you want.
KevinHall at 2007-11-11 1:26:06 >
# 2 Re: Normal Distribution Random Number
Hello,

A good method to generate random numbers with a probability distribution y = f(x) is as in the steps given:

1. Seed the random number. One can use the function srand(time(NULL)) for this. It is best to introduce in the function which generates random numbers, to be run at the first time.

2. One can write a function which generates random numbers between values x0 and x1 as follows:

#include <time.h>
#include <stdlib.h>

double Random(double x0, double x1)
{
static bool Flag = false;
if (!Flag)
{
Flag = true;
srand((unsigned) time(NULL));
}
return x0 + (x1 - x0) * rand() / RAND_MAX;
}

Note that the seed generation is embedded in the function implementation and will be called the first time.

3. Determine the maximum y value of the function within the range of interest. Let it be y1. Minimum y value will normally be y0 = 0.

4. Generate two random numbers x = Random(x0, x1) and y = Random(y0, y1). Check whether y < f(x). Accept the random number x if the condition is true, discard it if it is not.

5. The set of random numbers thus generated will be as per the distribution function y = f(x).

For probability functions which extends upto infinity on one or both sides of the limits, one has to map it to finite limits by changing variable. x=+/- (infinity) can be mapped to z=+/- (Pi/2) if we change the variable to x=cos(z).

Best luck.
Pravin.
10-03-2004.
Pravin Kumar at 2007-11-11 1:27:06 >
# 3 Re: Normal Distribution Random Number
Originally posted by PravinKumar
A good method to generate random numbers with a probability distribution y = f(x) is as in the steps given:

...

Yes, this is fine in general, however for the most common distributions there is a better way. As stated in the FAQ I mentioned, one should look at Numerical Recipes in C for recommended practices. This Numerical Recipes section (http://lib-www.lanl.gov/numerical/bookcpdf/c7-2.pdf) specifically talks about normal distribution. The most efficient way to create the normal distribution is to take two uniform deviates on the interval (0,1) -- call them r1 and r2. To create the normal random deviates n1 and n2, the following code will work:

const double TWO_PI = 6.283185307179586476925286766559;

double temp1 = sqrt(-2.0*log(r1));
double temp2 = TWO_PI*r2

n1 = temp1*sin(temp2);
n2 = temp1*cos(temp2);

- Kevin
KevinHall at 2007-11-11 1:28:05 >