-
-
Save mmalone/d710793137ed0d6b8cb4 to your computer and use it in GitHub Desktop.
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
/** | |
* Unfortunately ECMAScript is not precise enough with its definition of | |
* Math.random(), so this parameter is implementation dependent. It should | |
* definitely be a power of two otherwise I'm pretty sure the algorithm below | |
* breaks while calculating the limit. | |
*/ | |
var MAX_RANDOM = Math.pow(2, 30); | |
/** | |
* CAVEAT: I knocked this together in a couple minutes. It could use some | |
* review. | |
* | |
* Returns a pseudo-random, uniformly distributed integer between 0 (inclusive) | |
* and the specified value (exclusive). | |
*/ | |
Math.randomInt = function Math_randomInt(n) { | |
if (n <= 0 || n > MAX_RANDOM) { | |
throw new RangeError('Parameter must be between 0 and ' + MAX_RANDOM); | |
} | |
var limit = (MAX_RANDOM - (MAX_RANDOM % n)) / MAX_RANDOM; | |
var rand = Math.random(); | |
while (rand >= limit) { | |
rand = Math.random(); | |
} | |
return Math.floor(rand * n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment