So you want to generate numbers with a standard normal distribution? Here's the code to do it:
#include <math.h>
double stdNormRand()
{
static bool cachedAnswer = false; // We create two at a time - we'll just remember the second for the next call
static double y1 = -1; // Where we store the memorized answer for every other call
double x1, x2, w, y2;
if (cachedAnswer) // Check if we already memorized an answer
{
cachedAnswer = false; // If we did, then next time around we need to compute 2 more
return y1; // Return the memorized answer!
}
do {
x1 = 2.0 * (double)rand() / (double)RAND_MAX - 1.0;
x2 = 2.0 * (double)rand() / (double)RAND_MAX - 1.0;
w = x1 * x1 + x2 * x2;
} while (w >= 1.0);
w = (double) sqrt((-2.0 * log(w))/w);
y1 = x1 * w;
y2 = x2 * w;
cachedAnswer = true; // y1 now holds the next number to be returned
return y2;
}