Created
May 8, 2015 00:51
-
-
Save smokymountains/877af22b385f62780ef7 to your computer and use it in GitHub Desktop.
Box-Muller Transform
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
#include <cstdlib> | |
#include <cmath> | |
#include <limits> | |
double generateGaussianNoise(double mu, double sigma) | |
{ | |
const double epsilon = std::numeric_limits<double>::min(); | |
const double two_pi = 2.0*3.14159265358979323846; | |
static double z0, z1; | |
static bool generate; | |
generate = !generate; | |
if (!generate) | |
return z1 * sigma + mu; | |
double u1, u2; | |
do | |
{ | |
u1 = rand() * (1.0 / RAND_MAX); | |
u2 = rand() * (1.0 / RAND_MAX); | |
} | |
while ( u1 <= epsilon ); | |
z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2); | |
z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2); | |
return z0 * sigma + mu; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment