Last active
March 11, 2018 01:32
-
-
Save atoponce/872e7dc90696015a151f03c800b2fc24 to your computer and use it in GitHub Desktop.
Uniform random number generators
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
// Citation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random | |
/* | |
* Getting a random number from [0, max) | |
*/ | |
// DO THIS (unbiased) | |
function getRandomInt(max) { | |
var low = (-max >>> 0) % max; | |
do { var n = Math.random() * 0x100000000 >>> 0; } while(n < low); | |
return n % max; | |
} | |
// NOT THIS (biased) | |
function getRandomInt(max) { | |
return Math.floor(Math.random() * max); | |
} | |
/* | |
* Getting a random number from [min, max] | |
*/ | |
// DO THIS (unbiased) | |
function getRandomIntInclusive(min, max) { | |
var range = (max - min) + 1; | |
var low = (-range >>> 0) % range; | |
do { var n = Math.random() * 0x100000000 >>> 0; } while(n < low); | |
return (n % range) + min; | |
} | |
// NOT THIS (biased) | |
function getRandomIntInclusive(min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment