【问题标题】:number of items to replace is not a multiple of replacement length error?要替换的项目数不是替换长度的倍数错误?
【发布时间】:2021-02-05 01:08:26
【问题描述】:

设置如下:假设标准的洗牌套牌有 52 张牌。仅使用蒙特卡罗方法来计算一副牌中前两张牌是 A 的近似概率。在开始实施时,将种子设置为 514。您应该模拟至少 10 万次实验以获得足够近似的答案。

这是我返回错误的代码:

cards <- c(1:52)

nTrials<-100000
results <-rep(NA, nTrials)#creating empty vector with 100000 NAs

for(i in 1:nTrials){
  sampled <- sample(x=cards, size=2, replace=TRUE)
  results[i]<-sampled
}
results

【问题讨论】:

    标签: r for-loop replace montecarlo


    【解决方案1】:

    您在for 循环的每次迭代中对两张卡片进行采样。所以你会在末尾有2 *nTrials 卡片,它是分配的results 大小的两倍。将卡片存储在列表中。

    让我们假设卡号 1、14、27 和 40 是 A。您可以使用%in% 检查样本卡是否为王牌,如果是则增加计数器。

    cards <- c(1:52)
    aces <- c(1, 14, 27, 40)
    nTrials<-100000
    results <- vector('list', nTrials)
    counter <- 0
    
    for(i in 1:nTrials){
      sampled <- sample(x=cards, size=2, replace=TRUE)
      results[[i]] <- sampled
      if(all(sampled %in% aces)) counter <- counter + 1
    }
    #Number of times two aces were enountered
    counter 
    #Probability
    counter/nTrials
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      相关资源
      最近更新 更多