Javascript function to generate random integers with nonuniform probabilities

烈酒焚心 提交于 2019-12-02 05:28:09

Just accumulate the probabilities and return an item for which current_sum >= random_number:

probs = [0.41, 0.29, 0.25, 0.05];

function item() {
    var r = Math.random(), s = 0;
    for(var i = 0; i < probs.length; i++) {
        s += probs[i];
        if(r <= s)
            return i;
    }
}

// generate 100000 randoms

a = [];
c = 0;
while(c++ < 100000) {
    a.push(item());
}

// test actual distibution

c = {}
a.forEach(function(x) {
    c[x] = (c[x] || 0) + 1;
});

probs.forEach(function(_, x) {
    document.write(x + "=" +  c[x] / a.length + "<br>")
});

Create a second parallel array with corresponding weights and use a "wheel" algorithm to get an index.

function randomWithProbability()
{
    var notRandomNumbers = [1,2,3,4];

    var w = [0.41, 0.29, 0.25, 0.05];
    var placehldr = 0;
    var maxProb = 0.41;
    var index = Math.floor(Math.random() * w.length);
    var i = 0;

     placehldr = Math.random() * (maxProb * 2);
    while(placehldr > index )
    {
        placehldr -= w[index];
        index = (index + 1) % w.length
    }

    return (notRandomNumbers[index]);

}

This video has a good explanation as to why it works, it's easier to understand with the visual representation. https://www.youtube.com/watch?v=wNQVo6uOgYA

user515430

There is an elegant solution only requiring a single comparison due to A. J. Walker (Electronics Letters 10, 8 (1974), 127-128; ACM Trans. Math Software 3 (1977), 253-256) and described in Knuth, TAOCP Vol. 2, 120-121. You can also find a description here, generate random numbers within a range with different probabilities.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!