【问题标题】:Coin flip simulation using R使用 R 进行硬币翻转模拟
【发布时间】:2020-05-14 11:39:34
【问题描述】:

我正在尝试模拟反复翻转的有偏硬币,直到连续出现 2 个正面或连续出现 2 个反面(然后翻转停止)。我想求概率P(连续两个正面出现在连续两个反面之前)。

寻求帮助将“尾巴”翻转到循环中。谢谢

 flip <- function(bias_p) {                           
    n_flips <- 0                                           
    head <- 0
    tail <- 0
    while (head != 2 & tail != 2) {                                 
       n_flips <- n_flips + 1
       head_flips <- sample(c(1,0), 1, prob = c(bias_p, 1 - bias_p))
       if(head_flips == 1) ((head <- head + 1) & (tail <- 0))
       else ((tail <- tail + 1) & (head <- 0))
       } 
    return(c(head, tail))
    }  
 y <- replicate(5000, flip(0.8))
 length(which(y[1,] ==2)) / (ncol(y)) 

【问题讨论】:

  • 你能展示你目前拥有的代码吗,包括你目前尝试编写一个循环?

标签: r statistics simulation probability distribution


【解决方案1】:

为了使您当前的方法发挥作用,我必须进行一些更改:

  • 每次迭代仅生成一次翻转。目前,您每次迭代都会生成两个完全独立的随机结果 - hfliptflip 可能彼此不一致
  • 如果翻转是一个头,添加到nheads并将ntails重置为0
  • 如果翻转是尾巴,添加到ntails并重置nheads

(使用{}换成if/else可以更清楚逻辑流程是什么,你当前的else只连接到它上面的那一行,而不是第一个if测试)

coin_flip <- function(head_p) {                           
    nflips <- 0                                           
    nheads <- 0
    ntails <- 0
    while (nheads != 2 & ntails != 2) {                                 
        nflips <- nflips + 1
        # Only generate 1 flip
        flip <- sample(c(1,0),1,prob=c(head_p,1-head_p))
        # If heads:
        if (flip == 1) {
            nheads <- nheads + 1
            # Reset tails counter
            ntails <- 0
        # There are only two possibilities for what 'flip'
        # can be (1 or 0), so we can just use else rather than 
        # testing for 0 specifically
        } else {
           ntails <- ntails + 1
           nheads <- 0
        }
    } 
    return(nflips)
}

如果你需要函数输出2个正面还是2个反面,你可以将return(nflips)替换为return(nheads == 2):如果2个正面,这个函数将输出1,如果2个反面,则输出0。

【讨论】:

  • 感谢您的帮助,我相信我使用您提到的类似方法解决了这个问题。将编辑我的原始帖子
猜你喜欢
  • 1970-01-01
  • 2018-07-27
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 2020-07-17
  • 2019-01-07
相关资源
最近更新 更多