A great little JavaScript function for generating random Gaussian/Normal/Bell-Curve numbers

May 30, 2012 | No comments

Have you ever needed to generate random numbers that clustered around the center value? I have, and I found this little gem from Colin Godsey. Here’s the function:

Math.nrand = function() {
	var x1, x2, rad, y1;
	do {
		x1 = 2 * this.random() - 1;
		x2 = 2 * this.random() - 1;
		rad = x1 * x1 + x2 * x2;
	} while(rad >= 1 || rad == 0);
	var c = this.sqrt(-2 * Math.log(rad) / rad);
	return x1 * c;
};

I won’t pretend to understand how the math works, but I will show you a demo so you can get a picture of how you might use this: Generating a Random Gaussian Number with Javascript.

Tagged:

Leave a Reply