数字非均等分布的随机数生成器
Random number generator with non-equal distribution of numbers
我知道我可以使用
var rolls = [];
for (var i=0; i<100; i++) {
rolls.push(Math.floor(6 * Math.random()) + 1);
}
用一个骰子获得 100 卷。
但是,如果它是一个魔法骰子,每个数字出现的次数不均怎么办?
所以不是每个数字出现 1/6 的时间,而是数字 1-4 每个出现 10% 的时间,而 5 出现 20% 的时间,其余 6 个出现 100%- 20%-4*10% = 40% 的时间。
如何制作这样一个可以轻松调整分布的随机数生成器?
您可以创建一个具有所需分布的集合,例如
var distribution = [1,1,1,2,2,3];
var randomItem = new Random().Next(distribution.Length);
if(randomItem == 1)
{
//do something with with probability 50%
}
else if (randomItem == 2)
{
//do something with with probability 33%
}
else if (randomItem == 3)
{
//do something with with probability 17%
}
现在您可以添加应针对每种情况执行的代码
您可以使用带有概率的数组并对照随机值进行检查和计数。
此函数首先将 return 值设置为最后一个可能的索引并迭代,直到其余随机值小于实际概率。
概率之和必须为一。
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; }
我知道我可以使用
var rolls = [];
for (var i=0; i<100; i++) {
rolls.push(Math.floor(6 * Math.random()) + 1);
}
用一个骰子获得 100 卷。
但是,如果它是一个魔法骰子,每个数字出现的次数不均怎么办?
所以不是每个数字出现 1/6 的时间,而是数字 1-4 每个出现 10% 的时间,而 5 出现 20% 的时间,其余 6 个出现 100%- 20%-4*10% = 40% 的时间。
如何制作这样一个可以轻松调整分布的随机数生成器?
您可以创建一个具有所需分布的集合,例如
var distribution = [1,1,1,2,2,3];
var randomItem = new Random().Next(distribution.Length);
if(randomItem == 1)
{
//do something with with probability 50%
}
else if (randomItem == 2)
{
//do something with with probability 33%
}
else if (randomItem == 3)
{
//do something with with probability 17%
}
现在您可以添加应针对每种情况执行的代码
您可以使用带有概率的数组并对照随机值进行检查和计数。
此函数首先将 return 值设置为最后一个可能的索引并迭代,直到其余随机值小于实际概率。
概率之和必须为一。
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; }