Seeing as bromer needed a normalvariate function in C for some cluster project at DIKU, I thought it might be a good deal of fun to port it from python. That plus I have no clue what so ever about what the function does.
Without further delay, here is my first C code for a long time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #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; } |
You should seed your RNG with the process ID. That should be enough for any purpose.
Agreed. That seems like the logical thing to do :)