Monte Carlo 模式模拟
Monte Carlo Simulation for Pattern
我正在编写一个 Monte Carlo 模拟来检查有多少次 y 没有紧挨着另一个 y。我想出了一个由 40 个 x 和 10 个 y 组成的向量,它们被放置在向量中的随机位置。我的目标是计算向量中没有任何相邻 y 的概率。这是我尝试过的:
nrep = 100000
count = 0
for (i in 1:nrep) {
x = sample(c(rep('x', 40), c(rep('y', 10))))
if (x[i]!=x[i+1] && x[i+1]!=x[i+2]) count = count + 1
}
print(count/nrep)
结果是一个很小的数字,我觉得没有意义。
if
部分不正确。我们可以使用 head
/tail
来检查连续的元素,看看在一次迭代中是否有 any
两个连续的 'y'
。
nrep = 100000
count = 0
set.seed(2020)
for (i in 1:nrep) {
x = sample(rep(c('x', 'y'), c(40, 10)))
if(any(head(x, -1) == 'y' & tail(x, -1) == 'y')) count = count + 1
}
count/nrep
#[1] 0.891
我正在编写一个 Monte Carlo 模拟来检查有多少次 y 没有紧挨着另一个 y。我想出了一个由 40 个 x 和 10 个 y 组成的向量,它们被放置在向量中的随机位置。我的目标是计算向量中没有任何相邻 y 的概率。这是我尝试过的:
nrep = 100000
count = 0
for (i in 1:nrep) {
x = sample(c(rep('x', 40), c(rep('y', 10))))
if (x[i]!=x[i+1] && x[i+1]!=x[i+2]) count = count + 1
}
print(count/nrep)
结果是一个很小的数字,我觉得没有意义。
if
部分不正确。我们可以使用 head
/tail
来检查连续的元素,看看在一次迭代中是否有 any
两个连续的 'y'
。
nrep = 100000
count = 0
set.seed(2020)
for (i in 1:nrep) {
x = sample(rep(c('x', 'y'), c(40, 10)))
if(any(head(x, -1) == 'y' & tail(x, -1) == 'y')) count = count + 1
}
count/nrep
#[1] 0.891