Last Updated: September 09, 2019
·
1.06K
· 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);

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside