Given the following "Random Integer between range X and Y" function:
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
* from: http://stackoverflow.com/a/1527820/1148249
*/
function get_random_int(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
We can run the following test to confirm the randomness:
var i = 0; // counter for looping.
var results = {}; // store the results of running get_random_int
var min = 0;
var max = 9;
for(i = min; i <= max; i++) {
results[i] = 0; // initialize results to zero;
}
i = 0; // reset/reuse i counter.
var test_count = 10000000;
while(i < test_count) {
var r = get_random_int(min, max);
results[r]++; // increment the count for a given random number
i++;
}
Object.keys(results).forEach(function(k) {
results[k] = results[k].toString() + ' > ' + (results[k] / test_count * 100).toFixed(3) + ' %';
});
console.log(JSON.stringify(results, null, 2));
Given the following "Random Integer between range X and Y" function:
We can run the following test to confirm the randomness:
Which outputs:
Which is a pretty decent distribution...