Generate random integers with probabilities

前端 未结 5 845
离开以前
离开以前 2020-11-30 02:27

I\'m a bit confused about how to generate integer values with probabilities.

As an example, I have four integers with their probability values: 1|0.4, 2|0.3, 3|0.2,

5条回答
  •  甜味超标
    2020-11-30 02:57

    I suggest to use a continuous check of the probability and the rest of the random number.

    This function sets first the return value to the last possible index and iterates until the rest of the random value is smaller than the actual probability.

    The probabilities have to sum to one.

    function getRandomIndexByProbability(probabilities) {
        var r = Math.random(),
            index = probabilities.length - 1;
    
        probabilities.some(function (probability, i) {
            if (r < probability) {
                index = i;
                return true;
            }
            r -= probability;
        });
        return index;
    }
    
    var i,
        probabilities = [0.4, 0.3, 0.2, 0.09, 0.01 ],
        count = {},
        index;
    
    probabilities.forEach(function (a) { count[a] = 0; });
    
    for (i = 0; i < 1e6; i++) {
        index = getRandomIndexByProbability(probabilities);
        count[probabilities[index]]++
    }
    
    console.log(count);

提交回复
热议问题