我只需要你对Monte Carlo Simulations的帮助。这就是问题所在。
在一卷两个骰子上,总共七个以1/6的概率发生。 在100个掷骰子中,五个概率是多少 连续七卷会发生?
(这是M. Meerschaert的数学建模和模拟练习)
我使用R:
创建了一个伪代码dice.sims1 = function(trials){
occur
for (j in 1:trials){
x = 0
y = 0
n = 0
result = NULL
while (n<100){
n = n+1
result[n] = sample(1:6,1) + sample(1:6,1)
if(result[n] == 7){
x = x+1
}else {x = 0}
if(x>=5){
y = y+1
}
}
occur[j] = y
}
print(mean(occur)/100)
}
这是对的吗?如果是这样,我如何解释我的结果? 如果不正确,你可以帮我纠正吗?
谢谢你,祝你有个美好的一天。
答案 0 :(得分:1)
除了代码中的错误外,还有一个不明确的情况 - 如果你有6卷7连续,它是否算作一个或两个?
你把它算作两个
if(x>=5){
y = y+1
}
然后连续7卷会使它等三个。
更新
dice.sims1 = function(trials) {
occur = rep(0, times=trials)
for (j in 1:trials) {
x = 0
y = 0
n = 0
while (n<100) {
n = n + 1
result = sample(1:6,1) + sample(1:6,1)
if(result == 7){
x = x+1
} else {
x = 0
}
if(x>=5) {
y = y+1
x = 0 # !!! unclear problem setup
}
}
occur[j] = y
}
mean(occur)
}
set.seed(12345)
print(dice.sims1(10000))
将生成带有标记线的0.0109和带有标记线的0.0131
更新II
没有数组的版本,直接求和
dice.sims <- function(trials) {
s <- 0L
for (i in 1:trials) {
ncons <- 0L
for(k in 1:100) {
roll <- sample.int(6,1) + sample.int(6,1)
if (roll == 7L) {
ncons <- ncons + 1L # good roll
} else {
ncons <- 0L # bad one, back to square one
}
if (ncons >= 5L) {
s <- s + 1L
# ncons <- 0L # start from the beginning
}
}
}
as.numeric(s)/as.numeric(trials)
}