R 编写一个程序,告诉be有多少个观测值在100、1000、10000个转鼓后得到6
试图创建一个代码,给我一个理论概率,以及一个人掷骰子4次的机会的模拟估计,如果他们掷骰子6并打印它们之间的差异。但是,我的代码不是在R不识别函数的情况下运行的 您的函数缺少一个括号:R 编写一个程序,告诉be有多少个观测值在100、1000、10000个转鼓后得到6,r,R,试图创建一个代码,给我一个理论概率,以及一个人掷骰子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
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)
}
}
sixes\u rep我建议使用一种更高效的编码方式
这将使用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
sample(1:6,size=4,replace=TRUE)
是模拟4个骰子卷的更好方法。另一个建议是,您没有使用此部分total
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 <- 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