get a normally distributed random number in csharp

To generate a normally distributed random number in C#, we can make use of the Box-Muller transform. Here's an example implementation:

main.cs
public static double NextGaussianDouble(Random random, double mean, double stdDev)
{
    double u1 = 1.0 - random.NextDouble();
    double u2 = 1.0 - random.NextDouble();
    double stdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
    double scaled = mean + stdDev * stdNormal;
    return scaled;
}
325 chars
9 lines

This method takes three parameters: a Random instance for generating the uniform random numbers, the mean of the distribution, and the standard deviation of the distribution. It then generates two uniform random numbers, uses them to compute a standard normal random variable using the Box-Muller transform, and scales the result to the desired mean and standard deviation.

We can use this method like this:

main.cs
Random random = new Random();
double randNum = NextGaussianDouble(random, 0, 1); // mean of 0, standard deviation of 1
119 chars
3 lines

This will generate a normally distributed random number with a mean of 0 and a standard deviation of 1.

gistlibby LogSnag