如何在 R 中模拟一个鞅过程问题?

How to simulate a martingale process problem in R?

100 人正在观看 theater.At 节目结束时所有人都在参观更衣室,以便将他们的 coats.The 在更衣室工作的人全部归还给人们的外套random.The 参与者,他们会选择正确的外套 leave.The 其他选择错误的参与者,将外套还给该男子,该男子再次随机归还 coat.The 当所有顾客的过程结束时剧院收回他们的右外套。

我想在 R 中模拟这个 mar 过程,以便找到这个过程结束的预期时间。 但我不知道怎么办。有什么帮助吗? 类似于:



# 100 customers
x = seq(1,100,by=1);x
# random sample from x 
y = sample(x,100,replace=FALSE)
x==y
# for the next iteration exclude those how are TRUE and run it again until everyone is TRUE


预期时间是需要多少次迭代。

或者像这样的东西:


n = 100
X = seq(1,100,by=1)
martingale = rep(NA,n)

iterations = 0
accept     = 0
while (X != n) {
  iterations =  iterations + 1
  y = sample(1:100,100,replace=FALSE)
  if (X = y){ 
    accept = accept + 1
    X = X+1
    martingale [X] = y
  }
}
accept
iterations

我没有听从你上面的讨论,我不完全确定这是否是你想要的,但我的理由如下:

  • 你有N个人,让他们排队。
  • 第一轮第一人有1/N次机会穿对衣服
  • 此时你有两个选择。 Eitehr person 1 穿对了还是穿错了。
  • 如果人 1 穿对了衣服,那么人 2 有 1/(N-1) 的机会穿对了衣服。如果第 1 个人没有得到正确的衣服,第 1 个人留在池中(最后),第 2 个人也有 1/N 的概率得到正确的衣服。
  • 你继续分配这些概率,直到所有 N 个人都见过店员一次。然后你把那些穿对衣服的人挑出来,重复第一步,直到每个人都穿对衣服。
  • 出于模拟目的,您当然要将整个过程重复 1000 或 10000 次。

如果我没理解错的话,您对迭代次数很感兴趣,即店员必须多久检查一次整个队列(或剩下的队列)直到每个人都拿到衣服。

图书馆(tidyverse)

people <- 100
results <- data.frame(people     = 1:people,
                      iterations = NA)

counter <- 0
finished <- 0

while (finished < people)
{
  loop_people <- results %>%
    filter(is.na(iterations)) %>%
    pull(people)

  loop_prob <- 1/length(loop_people)
  loop_correct <- 0

  for (i in 1:length(loop_people))
  {
    correct_clothes_i <- sample(c(0,1), size = 1, prob = c(1-loop_prob, loop_prob))
    if (correct_clothes_i == 1)
    {
      results[loop_people[i], 2] <- counter + 1
      loop_correct <- loop_correct + 1
      loop_prob <- 1/(length(loop_people) - loop_correct)
    }
  }
  counter <- counter + 1
  finished <- length(which(!is.na(results$iterations)))
}

max(results$iterations)

[1] 86

head(results)

  people iterations
1      1          7
2      2         42
3      3         86
4      4         67
5      5          2
6      6          9

results$iterations 列包含每个人正确穿衣的迭代次数,因此 max(results$iterations) 给出循环总数。

我没有证据,但根据经验和直觉,所需的迭代次数应该接近 N。

一种方法如下(以10个人为例,打印语句是不必要的,只是为了展示每次迭代做了什么):

set.seed(0)
x <- 1:10
count <- 0
while(length(x) > 0){
  x <- x[x != sample(x)]
  print(x)
  count <- count + 1
}

# [1]  1  2  3  4  5  6  7  9 10
# [1] 3 4 5 6 7 9
# [1] 3 4 5 6 7
# [1] 3 4 5 6 7
# [1] 3 4 5 6 7
# [1] 3 4 5 6 7
# [1] 3 4 5 6 7
# [1] 3 4 5 6 7
# [1] 3 6
# 
count
# [1] 10

对于循环中的每一步,它都会删除 x 的值,其中客户已随机分配了他们的外套,直到还剩 none。

要使用此代码获取 100 人的预期时间,您可以将其扩展为:

set.seed(0)
nits <- 1000 #simulate the problem 1000 times
count <- 0
for (i in 1:nits){
  x <- 1:100
  while(length(x) > 0){
    x <- x[x != sample(x)]
    count <- count + 1/nits
  } 
}
count
# [1] 99.901

我在没有证据的情况下假设 n 个人的预期时间是 n 次迭代 - 当我尝试 50、100 或 200 个人时,这似乎非常接近。