Создание цикла for, который действует как счетчик, но счетчик неправильно подсчитывает - PullRequest
0 голосов
/ 23 января 2019

У меня есть цикл for, который подсчитывает всякий раз, когда в игре 4 броска костей, он будет учитываться каждый раз, когда он возвращает выигрыш, который будет по крайней мере 1 6 в игре.Однако, когда я бегу с несколькими повторениями, мой счетчик получает только 1.

sixes_rep <- function(n=4, r){
  total=0
  for (i in 1:r){
    if (any(ceiling(6*runif(n)) == 6)){
      total=total+1
       }
    } 
    # n is the number of dice
    # r is the number of replicates (capital N in the text)
    obs <-(total/r)

    theor <- (1-(5/6)^n)
    difference <- obs-theor


    cat("Theoretical prob of at least one six in", n, "dice is:", theor, "\n")
    cat("Empirical prob of at least one six after", r,"replications is:", obs, "\n")
    cat("the difference is", difference ,"\n")
    cat("trues",total)
    return(difference)
  }
}

# Sample output:
# Theoretical prob of at least one six in 4 dice is: 0.5177469 
# Empirical prob of at least one six after 10000 replications is: 0.5175 
# the difference is -0.0002469136 
# do not modify this code chunk
# a few test cases to see if your code works
set.seed(1)
sixes_rep(4, 100)
sixes_rep(4, 100)
sixes_rep(4, 1000)
sixes_rep(4, 1000)
sixes_rep(4, 1000)
sixes_rep(4, 10000)
sixes_rep(4, 10000)
sixes_rep(4, 10000)

1 Ответ

0 голосов
/ 24 января 2019

Вам не нужен явный цикл for, следующий код использует replicate, чтобы сделать то же самое и более читабелен.

sixes_rep <- function(n = 4, r){
  draws <- replicate(r, sample(6, 4, TRUE))
  total <- sum(draws == 6)
  obs <- total/r

  theor <- 1 - (5/6)^n
  difference <- obs - theor

  cat("Theoretical prob of at least one six in", n, "dice is:", theor, "\n")
  cat("Empirical prob of at least one six after", r, "replications is:", obs, "\n")
  cat("the difference is", difference ,"\n")
  cat("trues", total, "\n")
  return(difference)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...