Skip to content

Instantly share code, notes, and snippets.

@madssj
Created June 4, 2013 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madssj/5704537 to your computer and use it in GitHub Desktop.
Save madssj/5704537 to your computer and use it in GitHub Desktop.
#include <math.h>
#include <stdlib.h>
#define NV_MAGICCONST 1.7155277699214135 /* (4 * exp(-0.5) / sqrt(2.0)); */
#define MAX_RANDOM 2147483647 /* (2 ** 31) - 1; */
/*
* normalvariate ported from python's stdlib (random.normalvariate).
* released under the same licence as that (python license).
*
* remember to initialize the random engine before calling this function.
*/
double normalvariate(double mu, double sigma) {
double u1, u2, z, zz;
for (;;) {
u1 = ((float)random()) / MAX_RANDOM;
u2 = 1.0 - (((float)random()) / MAX_RANDOM);
z = NV_MAGICCONST * (u1 - 0.5) / u2;
zz = z * z / 4.0;
if (zz <= -(log(u2))) {
break;
}
}
return mu + z * sigma;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment