.NET style random generator with a normal or Gaussian distribution in C#

Recently I was looking for a .NET style random generator with a normal or Gaussian distribution. I found a nice example on Koders.com, which usses the Box-Muller transformation, and build the algorithm into a class derived from System.Random. A mean of 0.5 and standard deviation of 1/2pi is used to keep the values returned by Sample() between 0 and 1. Values falling outside the range [ 0.0, 1.0 ) are replace by the next sample. It might not be perfect for scientific use, but it’s good enough to suit my needs.

public class RandomNormal : Random
{
private double cache;
private bool isCacheFilled = false;
const double mean = 0.5;
const double standardDeviation = 0.5 / Math.PI;
private double Trunc(double value)
{
if (value < 0.0 || value >= 1.0) return this.Sample();
return value;
}
protected override double Sample()
{
if (isCacheFilled)
{
isCacheFilled = false;
return cache;
}
double r = 0.0;
double x = 0.0;
double y = 0.0;
do
{
x = 2.0 * base.Sample() - 1.0;
y = 2.0 * base.Sample() - 1.0;
r = x * x + y * y;
}
while (r >= 1.0 || r == 0.0);
double z = Math.Sqrt(-2.0 * Math.Log(r) / r);
cache = Trunc(mean + standardDeviation * x * z);
isCacheFilled = true;
return Trunc(mean + standardDeviation * y * z);
}
}

This entry was posted on Monday, March 31st, 2008 at 07:41 and is filed under .NET. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.