get a random number from a normal distribution with a mean of 0 and a standard deviation of 1 in csharp

To get a random number from a normal distribution with a mean of 0 and a standard deviation of 1 in C#, you can use the Random class from the System namespace and the Box-Muller transform.

Here's the code:

main.cs
Random rand = new Random();
double u1 = 1.0 - rand.NextDouble(); // uniform(0,1] random doubles
double u2 = 1.0 - rand.NextDouble();
double normal = Math.Sqrt(-2.0 * Math.Log(u1)) *
               Math.Sin(2.0 * Math.PI * u2); // random normal(0,1)
249 chars
6 lines

This code generates two random numbers from a uniform distribution and uses them to generate a random number from a normal distribution using the Box-Muller transform. The resulting number will have a mean of 0 and a standard deviation of 1.

gistlibby LogSnag