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;
}
@jmenashe
Copy link

jmenashe commented Feb 27, 2025

@NightElfik Little late to the party but here's my response regarding the independence of variables Z0 and Z1.

the only difference is cos/sin of the same angle and that is somehow enough to guarantee independence

I think the problem here might be due to the fact that Z0 and Z1 are simultaneously a) statistically independent of one another, and b) correlated with the values U1, U2, and polar coordinates R, θ.

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 Z0 can you tell me anything about Z1? Not really; if we pick an arbitrary value for Z0, then for any value Z1 we can find some combination of R and θ to satisfy the Box-Muller equations. So if we don't know U1, U2, R, or θ then Z0 tells us nothing about Z1. If we learn something about U1, U2, R, or θ, though, then Z0 may become more useful, because those four variables are also correlated with Z1.

Conversely, if I know that Z0 is positive, then that would tell me that θ is bounded by ±π/2, which makes sense because Z0 is correlated with θ.

You may want to take a look at the Conditional Dependence article for related info.

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