samedi 23 septembre 2017

Generating random indexes

When you want to generate random indexes to use on an array, make sure you use Math.floor instead of Math.round or your randomness could suffer.

Some novice programmers might generate a random index like this:

Math.round(Math.random() * LENGTH_OF_ARRAY);

But using Math.round has some issues. What you actually want to use is Math.floor:

Math.floor(Math.random() * LENGTH_OF_ARRAY);

Frequencies for array using both round and floor methods. The round method shows that the indexes 0 and array length + 1 are only half as likely to be generated

You can run the experiment yourself here: http://ift.tt/2wIfxh7




Aucun commentaire:

Enregistrer un commentaire