Created
April 10, 2011 21:39
-
-
Save serialhex/912753 to your computer and use it in GitHub Desktop.
returns a normally distributed random number...
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
// lots of code... | |
/// Returns a Gaussian or Normal random number. | |
/// By default the mean = 0 and variance = 1 | |
/// Using the polar form of the Box-Muller transform. | |
/// http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Polar_form | |
static inline float32_t normal_random(float32_t mean=0.0, float32_t variance=1.0) | |
{ | |
// sets up variables | |
float32_t rand_u = random(-1.0, 1.0); | |
float32_t rand_v = random(-1.0, 1.0); | |
float32_t rand_s = rand_u*rand_u + rand_v*rand_v; | |
float32_t ret = 0.0; | |
// makes sure rand_s is in the range (0,1] | |
while ((rand_s == 0) || (rand_s >= 1)) | |
{ | |
rand_u = random(-1.0, 1.0); | |
rand_v = random(-1.0, 1.0); | |
rand_s = rand_u*rand_u + rand_v*rand_v; | |
} | |
// the meat & potatos, and then the mean & variance shifting... | |
ret = rand_u*sqrt((-2.0*log(rand_s)/rand_s); | |
ret = variance*ret + mean; | |
return ret; | |
} | |
// lots more code :P |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment