Created
March 13, 2016 21:27
-
-
Save borogove/8cceb62b366add3c0021 to your computer and use it in GitHub Desktop.
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
/* Random number with Gaussian distribution. | |
Translated from Python's library random module to C# | |
by Russell Borogove. | |
*/ | |
const double NO_VALUE = -1e6f; | |
const double TAU = Math.PI*2.0; | |
static double gaussNext = NO_VALUE; | |
public static double Gaussian( double mu, double sigma ) | |
{ | |
/* | |
mu is the mean, and sigma is the standard deviation. This is | |
slightly faster than the normalvariate() function. | |
# When x and y are two variables from [0, 1), uniformly | |
# distributed, then | |
# | |
# cos(2*pi*x)*sqrt(-2*log(1-y)) | |
# sin(2*pi*x)*sqrt(-2*log(1-y)) | |
# | |
# are two *independent* variables with normal distribution | |
# (mu = 0, sigma = 1). | |
# (Lambert Meertens) | |
# (corrected version; bug discovered by Mike Miller, fixed by LM) | |
*/ | |
double z = gaussNext; | |
gaussNext = NO_VALUE; | |
if (z == NO_VALUE) | |
{ | |
double x2pi = UnityEngine.Random.value * TAU; | |
double g2rad = Math.Sqrt(-2.0 * Math.Log(1.0 - UnityEngine.Random.value)); | |
z = Math.Cos(x2pi) * g2rad; | |
gaussNext = Math.Sin(x2pi) * g2rad; | |
} | |
return mu + z*sigma; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment