【问题标题】:Dice Probability in R script [closed]R脚本中的骰子概率[关闭]
【发布时间】:2022-01-10 18:53:50
【问题描述】:

掷五个六面骰子。在 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。有没有其他方法可以在一行代码中编写它?还是浓缩?欢迎任何想法。

【问题讨论】:

  • 当然还有其他方法,但您到底在寻找什么?例如,您可以模拟掷骰子(类似于replicate(10000, sum(sample(1:6, 5, replace = TRUE)))),但这不会给出精确的解决方案。

标签: r probability dice


【解决方案1】:

来自this answer,引用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

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

【讨论】:

    猜你喜欢
    • 2013-07-18
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2013-06-12
    • 2015-07-03
    • 2013-12-29
    相关资源
    最近更新 更多