Skip to content

Instantly share code, notes, and snippets.

@atoponce
Last active March 11, 2018 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atoponce/872e7dc90696015a151f03c800b2fc24 to your computer and use it in GitHub Desktop.
Save atoponce/872e7dc90696015a151f03c800b2fc24 to your computer and use it in GitHub Desktop.
Uniform random number generators
// 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