【问题标题】:Coin Toss Monte Calro Simulating Exact Heads掷硬币蒙特卡罗模拟精确正面
【发布时间】:2019-09-04 09:15:12
【问题描述】:

我正在尝试编写一个用于不公平抛硬币的函数,它有四个输入:正面朝上的重量/概率、模拟次数、每个模拟的翻转次数以及我想要找到正面的确切数量获得的概率。

下面的函数返回我不理解的翻转部分的错误:

如果 (percent_heads == nheads) 计数器 1 并且只使用第一个元素 50

counter = 0
percent_heads = NULL
flip_function <- function(p, nheads, nflips, nsim){
  for(i in 1:nsim){
    flips <- sample(c("H","T"), size = nflips, replace = TRUE, prob = c(p, 1-p))
    percent_heads[i] <- length(which(flips == "H")) / nflips
    if(percent_heads == nheads) counter <- counter + 1
    }
  return(counter/nsim)
}

【问题讨论】:

  • 好的,我意识到错误的含义。所以我把它改成了: if(percent_heads[i] == nheads) counter = counter + 1 但是,这个函数每次只返回 0,即使我输入 (1, 100, 100, 10000)
  • 您的percent_heads 是比例,而nheads 是正面数量,因此它们通常不会相等,对​​吗?
  • 确实!我意识到,再看它一分钟。我是一个傻瓜。我在下面发布了我的新功能。如果可能的话,我会非常感谢有人帮我检查一下。

标签: r probability montecarlo


【解决方案1】:

我觉得我是个白痴。经过一番深思熟虑,我相信我得到了它的工作。请比我更聪明的人验证这是否按预期工作:

counter = 0
total_heads = NULL
flip_function <- function(p, nheads, nflips, nsim){
for(i in 1:nsim){
flips <- sample(c("H","T"), size = nflips, replace = TRUE, prob = c(p, 1-p))
total_heads[i] <- length(which(flips == "H"))
if(total_heads[i] == nheads) counter <- counter + 1
}
return(counter/nsim)
}

【讨论】:

  • 大致就好。最好在函数的第一行 (counter = 0) 中重置 counter。您可以与理论结果进行比较choose(nflips, nheads)*p^(nheads)*(1-p)^(nflips - nheads)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2013-01-02
  • 2012-04-26
相关资源
最近更新 更多