简体   繁体   English

在 R 中查找均值和方差

[英]Finding mean and variance in R

Is what I did correct in making a code for this problem?我在为这个问题编写代码时所做的是否正确?

My goal is to find the mean and variance of the total score of the team when for any pair of gamers who throw the same number, the team scores 1 point.我的目标是当任何一对投掷相同数字的玩家时,该团队得分 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 ) https://i.stack.imgur.com/PQh78.jpg

A quick mental run through the problem should tell us approximately the answer we should expect.对这个问题进行快速的心理分析应该可以告诉我们大致应该期望的答案。

If there are 10 players, then we have 5 pairs of players.如果有 10 个玩家,那么我们有 5 对玩家。 Think about any one of those pairs.想想其中任何一对。 Since the throws are all independent, it doesn't matter what the first player throws;由于投掷都是独立的,所以第一个玩家投掷什么都没关系; there is a one-in-six chance that the second player will throw the same number.第二个玩家有六分之一的机会掷出相同的数字。 Since the pair gets one point if the numbers match, the expected value in terms of points for a single pair throwing the dice will be 1 point * 1/6 = 1/6 points.由于如果数字匹配,这对得到一分,单对掷骰子的期望值将是 1 分 * 1/6 = 1/6 分。 Since there are five pairs on the team, the expected value of the team's score for each round will be 5 * 1/6 points = 5/6, or about 0.8333.由于球队有五对,因此球队每轮得分的期望值为 5 * 1/6 分 = 5/6,即 0.8333 左右。

When I run your code, I get a value for mean(scoreA) of 3.5, so clearly this isn't correct.当我运行您的代码时,我得到的mean(scoreA)值为 3.5,因此显然这是不正确的。

A naive implementation that simulates each throw would be:模拟每次投掷的简单实现是:

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))
}

And we can use the replicate function to run the simulation as many times as we like to get scoreA :我们可以使用replicate的 function 多次运行模拟以获得scoreA

rolls   <- 100000
players <- 10

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

And the results are:结果是:

mean(scoreA)
#> [1] 0.83605

var(scoreA)
#> [1] 0.6985974

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM