Skip to content

Instantly share code, notes, and snippets.

@tansey
Created December 7, 2011 18:49
Show Gist options
  • Save tansey/1444070 to your computer and use it in GitHub Desktop.
Save tansey/1444070 to your computer and use it in GitHub Desktop.
Sampling from a Gaussian Distribution in C#
public static double SampleGaussian(Random random, double mean, double stddev)
{
// The method requires sampling from a uniform random of (0,1]
// but Random.NextDouble() returns a sample of [0,1).
double x1 = 1 - random.NextDouble();
double x2 = 1 - random.NextDouble();
double y1 = Math.Sqrt(-2.0 * Math.Log(x1)) * Math.Cos(2.0 * Math.PI * x2);
return y1 * stddev + mean;
}
@NightElfik
Copy link

This paper compares accuracy of different methods

Fantastic reference, that is exactly something I was wondering about. Thanks for sharing!

When I was writing my first comment I was more worried about some systematic bias, not precision. For example, imagine a method that generates two random numbers as a = rand(); and b = 1.0-a. These two numbers are both from uniform random distribution but obviously they are strongly correlated to each other. Turns out that my intuition was not right and the box-muller method does not produce biased numbers.

Interestingly enough, the paper you shared says: Another form of the Box–Muller method is called the polar technique. This improves over the previous technique in being quicker since it makes fewer calls to the mathematical library and uses only one transcendental function, instead of three. and This method is advantageous of this method over the first form of Box–Muller’s method in spite of the fact that the algorithm discards 21% of the values of W in step 3..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment