Last Updated: April 24, 2021
·
565
· harshabn808

Math.random range is [0,1)? Not really!

While I was just wondering how random are the numbers generated by Math.random, observed one interesting thing about Math.random.

First I tried to generate 1000 random numbers using a loop. Well, it worked fine. 1000 random numbers between 0 to 1 were generated almost equally distributed within the range.

As I further increased the loop counter, beyond 100000, started observing that Math.random generated numbers outside the range of [0,1)

var array= {};
for (var i=0; i<1000000; i++) { 
    var random = Math.random().toString().substring(0,3);
    if(random.substring(0,2) != '0.') {
        console.log(random);
    }
    if (typeof array[random] != 'undefined') { 
        array[random]++;
    } else {
        array[random] = 1;
    }
} 

Try running this code snippet in Firebug or Chrome Developer Tools. You will see numbers between 1.x to 9.x being generated.