数字不等分布的随机数生成器 [英] Random number generator with non-equal distribution of numbers

查看:75
本文介绍了数字不等分布的随机数生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用

var rolls = [];
for (var i=0; i<100; i++) {
  rolls.push(Math.floor(6 * Math.random()) + 1);
}

用一个骰子获得 100 卷.

to get 100 rolls with a single die.

但如果它是一个魔法骰子,其中每个数字的出现都不相同怎么办?

But what if it is a magic die, where each number doesn't show up equally?

因此,不是每个数字出现 1/6 的时间,而是数字 1-4 每个出现 10% 的时间,而 5 出现 20% 的时间,其余 6 个数字出现 100%-20%-4*10% = 40% 的时间.

So instead of each number showing up 1/6th of the time, the numbers 1-4 each shows up 10% of the time whereas 5 shows up 20% of the time and the remaining 6 shows up 100%-20%-4*10% = 40% of the time.

如何制作这样一个可以轻松调整分布的随机数生成器?

How do you make such a random number generator where the distribution can easily be adjusted?

推荐答案

您可以使用具有概率的数组,并根据随机值进行检查和计数.

You could use an array with probabilities and check and count against a random value.

此函数首先将返回值设置为最后一个可能的索引并迭代,直到剩余的随机值小于实际概率.

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.

概率之和必须为 1.

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.1, 0.1, 0.1, 0.1, 0.2, 0.4],
    count = {},
    index;

probabilities.forEach(function (_, i) { count[i + 1] = 0; });

for (i = 0; i < 1e6; i++) {
    index = getRandomIndexByProbability(probabilities);
    count[index + 1]++;
}

console.log(count);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于数字不等分布的随机数生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆