Кодирование программы, которая сообщает, сколько наблюдений получают 6 после 100, 1000 10000 бросков - PullRequest
0 голосов
/ 23 января 2019

Попытка создать код, который дает мне теоретическую вероятность, а также имитационную оценку шансов в игре, где человек бросает кубик 4 раза, если он бросает 6 и печатает разницу между ними. мой код не работает с R не распознает функцию.

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

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)

Ответы [ 2 ]

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

Я предлагаю более эффективный для кода способ сделать это.

Используется replicate().Обратите внимание, что это не быстрее, чем ваше решение.

set.seed(123)
#this function just simulates the 4 rolls, and finds if any() is 6
my_rolls <- function(n){
  rolls <- sample(1:6, size = n, replace = T)
  any(rolls == 6) # number of 6s in a single roll
}

# now we replicate the 4-rolls r times
r <- 10
res <- replicate(r, my_rolls(4)) # simulate r times the rolls
#print(res)
#[1] TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE

Теперь давайте найдем разницу:

theor <- (1-(5/6)^4)
emp_prob <- sum(res)/r

emp_prob-theor
#[1] 0.1822531

Больше симуляций:

r <- 100000
res <- replicate(r, my_rolls(4))
emp_prob <- sum(res)/r
emp_prob-theor

Всеможно обернуть в my_sim() функцию, проще вызвать:

my_sim <- function(r, rolls=4) {

  res <- replicate(r, my_rolls(n=rolls))

  emp_prob <- sum(res)/r

  emp_prob-theor # we return just the difference as an example
}

my_sim(r=10, rolls=4)
#[1] -0.1177469
0 голосов
/ 23 января 2019

В вашей функции отсутствует скобка:

sixes_rep <- function(n=4, r){
  obs=0
  for (i in 1:r){
    if (any(ceiling(6*runif(n)) == 6)){
      obs=obs+1
      total<-obs
    } 
    # n is the number of dice
    # r is the number of replicates (capital N in the text)
    obs <-(obs/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")
    return(difference)
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...