在R中无法突破while循环

时间:2016-05-27 01:36:49

标签: r loops while-loop break

我的代码的目的是找到其中至少有2个人拥有相同生日的概率为50%的人数。

source('colMatches.r')
all_npeople = 1:300
days = 1:365
ntrials = 1000
sizematch = 2

N = length(all_npeople)

counter = 1
pmean = rep(0,N)

while (pmean[counter] <= 0.5)
{
  npeople = all_npeople[counter]
  x = matrix(sample(days, npeople*ntrials, replace=TRUE),nrow=npeople,
             ncol=ntrials)
  w = colMatches(x, sizematch)
  pmean[counter] = mean(w)
  counter = counter + 1
}

s3 = toString(pmean[counter])
s2 = toString(counter)
s1 = "The smallest value of n for which the probability of a match is at least 0.5 is equal to "
s4 = " (the test p value is "
s5 = "). This means when you have "
s6 = " people in a room the probability that two of them have the same birthday is 50%."
paste(s1, s2, s4, s3, s5, s2, s6, sep="")

当我运行该代码时,我得到“匹配概率至少为0.5的n的最小值等于301(测试p值为NA)。这意味着当你在一个房间里有301个人时他们两个生日相同的概率是50%。“所以while语句由于某种原因不能正常工作。虽然它应该在pmean [counter]不再小于或等于0.5时停止,但它一直在all_npeople中循环。

我知道pmean正在正确更新,因为当我测试它之后pmean [50] = 0.971。所以该列表确实是正确的,但while循环仍然不会结束。

* colmatches是一个函数,用于根据sizematch确定列是否具有一定数量的匹配项。因此,在这种情况下,它会查看x中定义的矩阵,并列出每列至少有2个相似值的列表,0表示没有匹配的每列。

2 个答案:

答案 0 :(得分:6)

我很钦佩你对这个问题进行编程的尝试,但R的美妙之处在于,大部分工作都是为你完成的:

qbirthday(prob = 0.5, classes = 365, coincident = 2)
#answer is 23 people.

您可能也有兴趣:

pbirthday(n, classes = 365, coincident = 2)

答案 1 :(得分:1)

如果代码的目的只是为了定义当其中至少有两个人生日相同的概率高于0.5时的人数,则可以用更简单的方式编写它:

# note that probability below is probability of NOT having same birthday

probability <- 1
people <- 1
days <- 365

while(probability >= 0.5){
    people <- people + 1
    probability <- probability * (days + 1 - people) / days
}

print(people)