Skip to content

Instantly share code, notes, and snippets.

@cmdr2
Created June 24, 2021 17:54
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 cmdr2/bf8bfe3ca20a13f6b81906f8802f5eb5 to your computer and use it in GitHub Desktop.
Save cmdr2/bf8bfe3ca20a13f6b81906f8802f5eb5 to your computer and use it in GitHub Desktop.
// returns a gaussian random function with the given mean and stdev.
function gaussian(mean, stdev) {
var y2;
var use_last = false;
return function() {
var y1;
if (use_last) {
y1 = y2;
use_last = false;
} else {
var x1, x2, w;
do {
x1 = 2.0 * Math.random() - 1.0;
x2 = 2.0 * Math.random() - 1.0;
w = x1 * x1 + x2 * x2;
} while (w >= 1.0);
w = Math.sqrt((-2.0 * Math.log(w)) / w);
y1 = x1 * w;
y2 = x2 * w;
use_last = true;
}
var retval = mean + stdev * y1;
if (retval > 0)
return retval;
return -retval;
}
}
// make a standard gaussian variable.
var standard = gaussian(100, 15);
// make a bunch of standard variates
for (i = 0; i < 1000; i++) {
console.log( standard() )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment