.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);
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: