首页 > 解决方案 > 使用 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 次方那么简单。有什么建议么?或者我可以遵循任何公式来得到这个结果?

标签: javascriptprobability

解决方案


从循环内的大理石数量(您感兴趣的类型和总数)中减去一个。为最后一个循环的累积概率保留一个外部变量,而不是幂。

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


推荐阅读