Skip to content

Instantly share code, notes, and snippets.

@IceCreamYou
Created September 18, 2014 04:12
Show Gist options
  • Save IceCreamYou/05785cde95258bd5c0fb to your computer and use it in GitHub Desktop.
Save IceCreamYou/05785cde95258bd5c0fb to your computer and use it in GitHub Desktop.
/**
* Returns a normally distributed random variable.
*
* Adapted from http://blog.yjl.im/2010/09/simulating-normal-random-variable-using.html
* To the extent I have the ability to do so, this code is released into the public domain.
*/
function random_normal(mean, variance) {
if (typeof mean === 'undefined') {
mean = 0.0;
}
if (typeof variance === 'undefined') {
variance = 1.0;
}
var V1, V2, S = 2;
while (S > 1) {
var U1 = Math.random();
var U2 = Math.random();
V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
}
var X = Math.sqrt(-2 * Math.log(S) / S) * V1;
X = mean + Math.sqrt(variance) * X;
return X;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment