我正在尝试使用R中的简单蒙特卡洛采样程序来回答以下问题:一个骨灰盒包含10个球。两个红色,三个白色和五个黑色。一次抽出全部10张,无需更换。找出绘制的第一个和最后一个球都是黑色的可能性。
我尝试了两种方法,但都没有用。
更长的方法对我来说更直观:
balls <- c(1:10) #Consider 1-5 black, 6-8 white, and 9-10 red.
pick.ball <- function(balls){
sample(x = balls, 1, replace = FALSE)
}
experiment <- function(n){
picks = NULL
keep <- NULL
for(j in 1:n){
for(i in 1:10){
picks[i] <- pick.ball(balls = balls)
}
keep[j] <- ifelse(picks[1] == any(1:5) & picks[10] == any(1:5), 1, 0)
}
return(length(which(keep == 1))/n)
}
这是我的第二种更简单的方法,它显示了我对重复循环的理解不足。不用理会它-它会永远持续下去。但是,如果有人可以帮助我更好地理解原因,那将不胜感激!
balls <- c(1:10) #Consider 1-5 black, 6-8 white, and 9-10 red.
pick.ball <- function(balls, n){
keep = NULL
for(i in 1:n){
picks <- sample(x = balls, 10, replace = FALSE)
keep[i] <- ifelse(picks[1] == any(1:5) & picks[10] == any(1:5), 1, 0)
repeat{
picks
if(length(keep) == n){
break
}
}
}
return(which(keep == 1)/n)
}
答案 0 :(得分:2)
这是我创建的循环。您可以根据需要将其包装在一个函数中。我没有使用数字编号,而是使用字母。
urn <- c(rep("B", 5), rep("W", 3), rep("R", 2))
# Set the number of times you want to run the loop
nloops <- 10000
# Create an empty data frame to hold the outcomes of the simulation
m <- structure(list(first = character(),
last = character(),
is_black = integer()),
class = "data.frame")
现在运行循环
set.seed(456)
for (j in 1:nloops) {
b <- sample(urn, 10, replace = FALSE)
m[j, 1:2 ] <- b[c(1, 10)]
m[j, 3] <- ifelse(m[j, 1] == "B" & m[j, 2] == "B", 1, 0)
}
head(m)
first last is_black
1 B W 0
2 B B 1
3 B B 1
4 R B 0
5 B R 0
6 R W 0
最后,答案:
# Proportion of cases where first and last ball drawn were black
sum(m[ , 3]) / nloops
# This was 0.22