jeudi 13 décembre 2018

JavaScript Random Number Generation: Unique 500 Integers in Space 10^6: Getting Collisions

Below is a very simple example of Random Integer generation in JS where I'm not "stretching the limits" by any means.

I'm only generating 500 unique random integers from a very large space, 10^6.

And yet, if you keep clicking the button, you'll occasionally see 499 or 498 unique ones out of the 500. It doesn't happen extremely often, but it happens maybe on every 10th or 15th click. Why is that? My space is 1 million. I don't expect to get collisions in a sample of 500 with the frequency of every 10th or 20th click.

To test, keep clicking the button and watch the console. Is JS' RNG really not of good quality?

function run() {
  var nums = new Set();

  for (var i = 0; i < 500; i++) {
    nums.add(randomInteger10to6th());
  }

  console.clear();
  console.log('Random 10^6 Unique Integer set: ' + nums.size);
}

function randomInteger10to6th() {
   return Math.round(Math.random() * Math.pow(10,6))
}
<button id="run" onclick="run();">Run 500 Random Integers, Space: 10^6</button>



Aucun commentaire:

Enregistrer un commentaire