javascript - 使用 JS 计算相关连续概率 n 次
问题描述
我有一个包含 n 种弹珠的数组,这是一个简化的示例:
let marbles = [
{variable: “Green marbles”, text: “Green marble”, amount: 10},
{variable: “Yellow marbles”, text: “Yellow marble”, amount: 12},
{variable: “Pink marbles”, text: “Pink marble”, amount: 8}
]
我希望用这个数组做的是计算连续获得绿色或黄色或粉红色大理石而不替换它的概率(意味着每次绘制大理石时它都是基板)。所以这里有一个例子:
in the first pick, the probability of getting a pink marble is:
8/30.
In the second pick, the probability is now:
7/29 * 8/30
In the third pick, the probability is now:
6/28 * 7/29 * 8/30
等等。我已经设法做到这一点来计算替换的概率,如下所示:
let withReplacementArray = []
let i
let total = marbles.reduce((prev, cur)=> {return prev + cur.amount}, 0)
marbles.forEach((cur)=> {
for(i=1; i<=total; i ++) {
withReplacementArray.push({
probability: (Math.pow(cur.amount, i))/(Math.pow(total, i)),
n: i,
text: cur.text
})
}
})
简而言之,这种方法不适用于计算没有放回的概率,因为它不再像将其提高到 i 次方那么简单。有什么建议么?或者我可以遵循任何公式来得到这个结果?
解决方案
从循环内的大理石数量(您感兴趣的类型和总数)中减去一个。为最后一个循环的累积概率保留一个外部变量,而不是幂。
let marbles = [
{variable: "Green marbles", text: "Green marble", amount: 10},
{variable: "Yellow marbles", text: "Yellow marble", amount: 12},
{variable: "Pink marbles", text: "Pink marble", amount: 8}
];
// say we want to pick green
let greenAmount = marbles[0].amount;
let total = marbles.reduce((a, { amount }) => a + amount, 0);
let lastProbability = 1;
while (greenAmount > 0) {
lastProbability = lastProbability * (greenAmount / total);
console.log(lastProbability);
greenAmount--;
total--;
}
// 10/30
// then 10/30 * 9/29
// etc
推荐阅读
- javascript - Angular 2 如何更新 Observables 数组?
- tensorflow - 使用 conda 安装后如何升级 tensorflow?
- matrix - 如何保存和检索flutter的Vector_math库的Matrix4对象?
- python - 如何执行从 Ionic 4 到 djangorestframework 的发布请求(带有数据)
- python - 如何将由各种 ASCII 码组成的 int 值转换为其对应的字符串?
- codenameone - CodenameOne后台发送短信与Android
- sql-server - 如何从没有时间戳的日期列中选择前 1 个日期?
- angular - 为什么在我的 Angular 应用程序中刷新页面或单击链接时,我的 auth0 令牌会过期?
- jquery - 为什么 barba.js 在 wordpress 上有问题?
- c - 在 C 中将方阵提高到 N 次方