## Generating Normally Distributed Data

There are many situations where I need to generate a set of numbers which is Normally distributed. By Normal, I mean Gaussian, or bell-shaped. There are many ways to do this but I usually prefer a technique called the Box-Muller algorithm which uses clever math to convert numbers from a uniform distribution to a Normal distribution. For example, if I define a Gaussian class which uses the Box-Muller algorithm as follows:

class Gaussian
{
private Random r;
private double mean;
private double standardDeviation;

public Gaussian(double mean, double sd)
{
r = new Random(0);
this.mean = mean;
this.standardDeviation = sd;
}

public double NextGaussian()
{
double u1 = r.NextDouble();
double u2 = r.NextDouble();
double left = Math.Cos(2.0 * Math.PI * u1);
double right = Math.Sqrt(-2.0 * Math.Log(u2));
double z = left * right;
return this.mean + (z * this.standardDeviation);
}
}

Then I can generate 1,000 random values which have a mean of 0.0 and a standard deviation of 1.0 like this:

Gaussian g = new Gaussian(0.0, 1.0);

for (int i = 0; i < 1000; ++i)
{
double x = g.NextGaussian();
Console.WriteLine(x.ToString(“F4”));
}

Alternatively I can group the results into categories of (less than -3), (-3, -2), (-2, -1), (-1, 0), (0, +1), (+1, +2), (+2, +3), (greater than +3), and transfer the results into Excel and produce a graph like the one below.