Skip to content

Instantly share code, notes, and snippets.

@smokymountains
Created May 8, 2015 00:51
Show Gist options
  • Save smokymountains/877af22b385f62780ef7 to your computer and use it in GitHub Desktop.
Save smokymountains/877af22b385f62780ef7 to your computer and use it in GitHub Desktop.
Box-Muller Transform
#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