-
-
Save ruzz311/0ce510792b317e7b6be93f6d0e752a18 to your computer and use it in GitHub Desktop.
Random number generating (Box-Muller)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Random = { | |
/** | |
* Numbers between ~( -2 to 2 ) | |
* http://stackoverflow.com/questions/75677/converting-a-uniform-distribution-to-a-normal-distribution | |
* http://c-faq.com/lib/gaussian.html | |
*/ | |
gaussian: function() { | |
var x1, x2, r; | |
do { | |
x1 = 2 * Math.random() - 1; | |
x2 = 2 * Math.random() - 1; | |
r = x1 * x1 + x2 * x2; | |
// Check if generated number is range [0,1] | |
} while (r >= 1 || r === 0); | |
return Math.sqrt(-2 * Math.log(r) / r) * x1; | |
}, | |
normalDist: function(mean, stdDev) { | |
return mean + (this.gaussian() * stdDev); | |
} | |
}; | |
for (var i = -20; i <= 20; i += .25) | |
document.write(Random.normalDist(0, i) + '<br />'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment