# [ACCEPTED]-C# Normal Random Number-random

See this CodeProject article: Simple Random Number Generation. The code 2 is very short, and it generates samples 1 from uniform, normal, and exponential distributions.

You might be interested in Math.NET, specifically 4 the Numerics package.

**Caveat**: The numerics package 3 targets .NET 3.5. You may need to use the 2 Iridium package if you are targeting an 1 earlier version...

Here is some C that returns two values (rand1 2 and rand2), just because the algorithm efficiently 1 does so. It is the polar form of the Box-Muller transform.

```
void RandVal (double mean1, double sigma1, double *rand1, double mean2, double sigma2, double *rand2)
{
double u1, u2, v1, v2, s, z1, z2;
do {
u1 = Random (0., 1.); // a uniform random number from 0 to 1
u2 = Random (0., 1.);
v1 = 2.*u1 - 1.;
v2 = 2.*u2 - 1.;
s = v1*v1 + v2*v2;
} while (s > 1. || s==0.);
z1 = sqrt (-2.*log(s)/s)*v1;
z2 = sqrt (-2.*log(s)/s)*v2;
*rand1 = (z1*sigma1 + mean1);
*rand2 = (z2*sigma2 + mean2);
return;
```

}

Sorry I don't have any code for you but 3 I can point you to some algorithms on Wikipedia. The algorithm you choose 2 I guess depends on how accurate you want 1 it and how fast it needs to be.

For those referencing this question, an 3 easy solution might be:

```
Random rand = new Random();
double normRand = alglib.invnormaldistribution(rand.NextDouble())
```

scale by mu and sigma 2 as needed.

The alglib library is available 1 at www.alglib.net

The MetaNumerics library, also .NET, will calculate 4 a normal distribution (and just about anything 3 else from statistics), super quickly. Have 2 a look at the Feature's page for more details. The 1 Codeplex page is here: http://metanumerics.codeplex.com/.

## MathNet

from second top answer

```
public static double GenerateRandomVariant(double mean,double deviation,System.Random rand=null, int factor=1)
{
rand = rand ?? new Random();
double randNormal=(MathNet.Numerics.Distributions.Normal.Sample(rand, mean , deviation));
return factor * randNormal;
}
```

## Box-Mueller Transform

from top answer via 1 link (twice as fast?)

by u/yoyoyoyosef Random Gaussian Variables

```
public static double GenerateRandomVariant(double mean, double deviation, System.Random rand=null, int factor = 1)
{
rand = rand ?? new Random();
double u1 = 1.0 - rand.NextDouble(); //uniform(0,1] random doubles
double u2 = 1.0 - rand.NextDouble();
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
double randNormal=(
mean + deviation * randStdNormal); //random normal(mean,stdDev^2)
return randNormal * factor;
}
```

More Related questions

We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.