在 R 中寻找均值和方差

Finding mean and variance in R

我为这个问题编写的代码是否正确?

我的目标是求任意一对投出相同数字的玩家,该队得 1 分时,该队总分的均值和方差。

die <- function(n){sample(1:6, n, replace = TRUE)}

A <- function(Die){
  int <- table(Die)
  sum(as.integer(int/2))
}

rolls <- 10000
players <- 10
scoreA <- sapply(1:rolls, function(x) {
  rolled <- die(players)
  A(rolled)
})

mean(scoreA)
var(scoreA)

(https://i.stack.imgur.com/PQh78.jpg)

快速思考 运行 解决问题应该会大致告诉我们应该得到的答案。

如果有 10 个玩家,那么我们有 5 对玩家。想想其中的任何一对。由于投掷都是独立的,因此第一个玩家投掷什么并不重要;有六分之一的机会第二位玩家会抛出相同的数字。由于如果数字匹配,该对将获得一分,因此一对掷骰子的 预期值 将是 1 分 * 1/6 = 1/6 分。由于球队有五对,球队每轮得分的期望值为5 * 1/6分= 5/6,即0.8333左右。

当我 运行 你的代码时,我得到的 mean(scoreA) 值为 3.5,很明显这是不正确的。

模拟每次抛出的简单实现是:

players_roll_once <- function(players) 
{
  # Ensure that only an even number of players on the team
  if(players %% 2 != 0) stop("Need an even number of players")
  
  # The first member of each pair rolls their dice
  first_members_rolls  <- sample(6, players / 2, replace = TRUE)

  # The second member of each pair rolls their dice
  second_members_rolls <- sample(6, players / 2, replace = TRUE)
  
  # Assign one for each time the first and second member of each pair match
  scored_a_point <- as.numeric(first_members_rolls == second_members_rolls)

  # Add up all the points the team got and return the answer
  return(sum(scored_a_point))
}

并且我们可以使用 replicate 函数来 运行 模拟任意多次,得到 scoreA:

rolls   <- 100000
players <- 10

set.seed(1) # Makes this reproducible
scoreA  <- replicate(rolls, players_roll_once(players))

结果是:

mean(scoreA)
#> [1] 0.83605

var(scoreA)
#> [1] 0.6985974