True or better Random numbers with Javascript

前端 未结 8 693
花落未央
花落未央 2020-11-28 08:41

I have all kinds of resources that rely on javascript random numbers. However, I\'ve been seeing a lot of problems where random isn\'t so random because of the way I\'m gene

8条回答
  •  萌比男神i
    2020-11-28 09:14

    While looking for an alternative for Math.random I stumbled on this question.

    While those are valid answers, the solution that worked for me was simply using Math.random twice.
    And use a modulus on the decimals of the float.
    Basically to increase the randomness.

    Maybe it might be usefull for some who were guided by google to this question.

    Here's a snippet with the function, and one that runs it a million times.

    function rand(min, max){
        return (Math.floor(Math.pow(10,14)*Math.random()*Math.random())%(max-min+1))+min;
    }
    
    // testing rand
    function rollRands(min, max, rolls) {
        let roll = 0, n = 0;
        let counts = {};
        
        for(let i = min; i <= max; i++){
            counts[i]=0
        }
    
        while (roll < rolls){
            roll++;
            counts[rand(min,max)]++;
        }
        return counts;
    }
      
    console.log(rollRands(36, 42, 1000000));

提交回复
热议问题