Write a truly inclusive random method for javascript

前端 未结 9 1481
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 11:25

Javascript\'s MATH object has a random method that returns from the set [0,1) 0 inclusive, 1 exclusive. Is there a way to return a truly random method that includes 1.

9条回答
  •  死守一世寂寞
    2020-11-30 11:44

    Since this question has been asked again, and I didn't read this approach here I'll add another answer.

    IMO the best you can do, without too much hassle would be:

    exclusive:

    //simply ignore the 0
    for(var rand=0; !rand;rand = Math.random());
    
    //or simpler:
    var rand = Math.random() || Math.random();
    //because the probability for two consecutive `0` is pretty much non existant.
    

    this doesn't even introduce an error, since we just excluded the possibility of returning 0, every other value between 0 and 1 has the same probability

    inclusive:

    var rand = Math.random() * 2;
    if(rand > 1) rand-=1;
    //so the 0 shares it's probability with the 1.
    

    just to be clear about how tiny the "error" is:

    • the probability for a 0 or a 1 is
      1 / Math.pow(2, 54) or about 5.55e-17
    • the probability for any other value between 0 and 1 is
      1 / Math.pow(2, 53) or about 11.1e-17

    and the whole random-function would be:

    function random(min, max, inclusive){
        var r = Math.random();
        if(inclusive)
            r = r>0.5? 2*r-1: 2*r;
        else 
            while(!r) r = Math.random();
    
        return r * (max - min) + min;
    }
    

    Edit: I'm not sure wether I make a mistake, but shouldn't the probability be fixed on the inclusive approach, if I add another bit to the zeroes and ones, and therefore duplicate their probability:

    var rand = Math.random() * 4;
    rand = (rand % 1) || (rand & 1);
    

提交回复
热议问题