Last active
March 18, 2016 03:33
-
-
Save danvanderboom/725efb7fe807434e0c6d to your computer and use it in GitHub Desktop.
Box-Muller normal distribution random number generator (Google App Script)
This file contains hidden or 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
function randnormal(minimum, mean, maximum, stdev) | |
{ | |
// start with two uniformly distributed random numbers | |
var rn1 = Math.random(); | |
var rn2 = Math.random(); | |
// Box-Muller transform | |
var r = Math.sqrt(-2 * Math.log(rn1)); | |
var theta = 2 * Math.PI * rn2; | |
var x = r * Math.cos(theta); // 1st of 2 random numbers generated | |
// transform 1st Box-Muller output to desired value space | |
var n = x * stdev + mean; | |
// if value within range, return result | |
if (n >= minimum & n <= maximum) | |
return n; | |
// 1st random number wasn't in range, so try 2nd random number | |
var y = r * Math.sin(theta); | |
n = y * stdev + mean; | |
// if still not in range, start over with another random pair | |
if (n < minimum | n > maximum) | |
return randnormal(minimum, mean, maximum, stdev); // try again | |
// 2nd value is in range, return results | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For use in Google Spreadsheets in code behind scripts.