How to get a random number from 0 to N-1

Just random number is not a problem, Math.random() gives you uniformly distributed random number between 0 and 1. The question happens when you try to get an integer random number in selected range out of this floating-point random number. As usual the problem is not to multiply it for range width, but to get every number in a range and no numbers out of range. Here is a practical solution.

Most popular numbers to generate are in the range from 0 to N-1, because this is a way to generate random index for an array (if N is array length, element has indexes from 0 to N-1). If you'll look to the code you will notice that originally code may produce -1, but it forced to 0. Will it change distribution? To say precisely - YES, practically - NO. Because out of all floating point values generator ust give you almost precisely 0 to fall to -1, which has a very low probability, so distribution practically will not change.

And here is an example how to do that:


Reload this page and see a different number:


And here is the code to implement this:

<script language="JavaScript"> function getRand(n) { var r = Math.floor(Math.random()*n-0.0001); if ( r < 0 ) { r=0; } return r; } </script> ... <script language=javascript> document.write(getRand(100)); </script>