gpt4 book ai didi

Javascript函数生成具有非均匀概率的随机整数

转载 作者:行者123 更新时间:2023-11-30 12:28:57 26 4
gpt4 key购买 nike

在 javascript(或 jquery)中有一个简单的函数可以得到四个整数及其概率值:1|0.41、2|0.29、3|0.25、4|0.05

如何根据概率生成这四个数字?

这个问题与此处发布的问题非常相似:generate random integers with probabilities

但是那里发布了解决方案:

function randomWithProbability() {
var notRandomNumbers = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4];
var idx = Math.floor(Math.random() * notRandomNumbers.length);
return notRandomNumbers[idx];
}

在评论中声明“动态创建 notRandomNumbers(给定数字及其权重/概率)”

这不足以满足我的需求。当概率为 10%、20%、60%、10% 时,这很有效。

在这种情况下,构造具有所需分布的 notRandomNumbers 很容易,而且数组大小很小。但在概率可能为 20.354%、30.254% 等的一般情况下,数组大小对于正确模拟情况来说会很大。

这个更普遍的问题是否有一个干净的解决方案?

编辑:谢谢 Georg,已接受解决方案,这是我的最终版本,可能对其他人有用。我已将累积计算拆分到一个单独的函数中,以避免在每次调用时额外添加以获得新的随机数。

function getRandomBinFromCumulative(cumulative) {
var r = Math.random();
for (var i = 0; i < cumulative.length; i++) {
if (r <= cumulative[i])
return i;
}
}
function getCummulativeDistribution(probs) {
var cumulative = [];
var sum = probs[0];
probs.forEach(function (p) {
cumulative.push(sum);
sum += p;
});
// the next 2 lines are optional
cumulative[cumulative.length - 1] = 1; //force to 1 (if input total was <>1)
cumulative.shift(); //remove the first 0
return cumulative;
}
function testRand() {
var probs = [0.1, 0.3, 0.3, 0.3];
var c = getCummulativeDistribution(probs);
console.log(c);
for (var i = 0; i < 100; i++) {
console.log(getRandomBinFromCumulative(c));
}
}

最佳答案

只需累加概率并返回一个 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>")
});

关于Javascript函数生成具有非均匀概率的随机整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28325453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com