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 hidden or 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
@NightElfik Little late to the party but here's my response regarding the independence of variables
Z0andZ1.I think the problem here might be due to the fact that
Z0andZ1are simultaneously a) statistically independent of one another, and b) correlated with the valuesU1,U2, and polar coordinatesR,θ.Another way to think about the statistical (in)dependence of two values is to consider whether knowing something about one can tell you anything about the other. In the case of Box-Muller, if you know the value of
Z0can you tell me anything aboutZ1? Not really; if we pick an arbitrary value forZ0, then for any valueZ1we can find some combination ofRandθto satisfy the Box-Muller equations. So if we don't knowU1,U2,R, orθthenZ0tells us nothing aboutZ1. If we learn something aboutU1,U2,R, orθ, though, thenZ0may become more useful, because those four variables are also correlated withZ1.Conversely, if I know that
Z0is positive, then that would tell me thatθis bounded by±π/2, which makes sense becauseZ0is correlated withθ.You may want to take a look at the Conditional Dependence article for related info.