R脚本中的骰子概率

Dice Probability in R script

掷五个六面骰子。在 R 中编写一个脚本来计算获得 15 到 20 之间的概率作为您的掷骰总和。首选精确解。

dice <- expand.grid(1:6, 1:6, 1:6, 1:6, 1:6)
dice.sums <- rowSums(dice)
mean(15 <= dice.sums & dice.sums <=20)
[1] 0.5570988



这是我的代码,答案恰好是 0.5570988。有没有其他方法可以在一行代码中编写它?还是浓缩一下?欢迎任何想法。

来自this answer, which references this answer

dDice <- Vectorize(function(k, m, n) {
  # returns the probability of n m-sided dice summing to k
  s <- 0:(floor((k - n)/m))
  return(sum((-1)^(s)*choose(n, s)*choose(k - s*m - 1, n - 1))/m^n)
}, "k")

sum(dDice(15:20, 6, 5))
#> [1] 0.5570988

请注意,我没有注意添加交替和项的顺序,因此可能需要将函数修改为 return 较大输入值的准确概率。