dimanche 10 mars 2019

Why is Math.floor(Math.random() * n) better than Date.now() % n to choose a random number between [0, n]?

I have been using Math.floor(Math.random() * someArray.length) for years to choose a random element in an array. I have always wondered why it is better than Date.now() % someArray.length. The latter seems to me much less error prone and must be faster (though, I haven't actually benchmarked it).

Notes:

  1. I don't need repeatability.
  2. This isn't run in a loop, so the function is called randomly throughout the application.
  3. This isn't for a simulation, so "more or less" random is good enough.



Aucun commentaire:

Enregistrer un commentaire