Created
December 7, 2011 18:49
-
-
Save tansey/1444070 to your computer and use it in GitHub Desktop.
Sampling from a Gaussian Distribution in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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();
andb = 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.
andThis 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.
.