Question 13.20

How can I generate random numbers with a normal or Gaussian distribution?


Here is one method, by Box and Muller, and recommended by Knuth:

#include <stdlib.h>
#include <math.h>

double gaussrand()
{
	static double V1, V2, S;
	static int phase = 0;
	double X;

	if(phase == 0) {
		do {
			double U1 = (double)rand() / RAND_MAX;
			double U2 = (double)rand() / RAND_MAX;

			V1 = 2 * U1 - 1;
			V2 = 2 * U2 - 1;
			S = V1 * V1 + V2 * V2;
			} while(S >= 1 || S == 0);

		X = V1 * sqrt(-2 * log(S) / S);
	} else
		X = V2 * sqrt(-2 * log(S) / S);

	phase = 1 - phase;

	return X;
}

See the extended versions of this list (see question 20.40) for other ideas.

References: Knuth Sec. 3.4.1 p. 117
Box and Muller, ``A Note on the Generation of Random Normal Deviates''
Press et al., Numerical Recipes in C Sec. 7.2 pp. 288-290


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback