Last Updated: September 09, 2019
·
785
· ranjan

Randomness about Math.random()

I was thinking about collision while using Math.random() earlier today, and it was interesting to run an experiment that how long it takes before Math.random() in JavaScript starts to show up previously repeated patterns.

Turns out it goes until about 63% times without repetition when run for 1 mn times.

The working jsfiddle is here.

var generateRandom = function(){
    var num = Math.floor((Math.random())*1000000);
    return num;
};

var checkCollision = function(){
    storage = [];
    for(var i=0; i<1000000; i++){
        var num = generateRandom();
        storage.push(num);  
    };
};

checkCollision();


//check for all numbers
console.log(storage.length);

// check for unique numbers
console.log(_.uniq(storage).length);