在 R 中,如何找到 f(x)=0.5 的 x

In R, how to find the x for which f(x)=0.5

我正在编写生日问题。我的代码:

> k = 100
> for (n in 1:100) {
+ prob =  1 - (0:(n-1))/365
+ k[n] = 1 - prod(prob) }
> plot(k)

我需要找到两个人生日相同的可能性约为 50% 的 n。有什么帮助吗?我尝试使用谷歌搜索,但只能找到有关流行发行版的信息。

尝试 stats 包中的以下内容...

 approx(k,1:100, xout = .5)

上面使用了最近的两个提供的点之间的线性插值,我可能会被跳过,因为它不准确...

但是如果我们在做生日题,我猜我们是在学习编码而不是发射火箭,所以也许它足够接近了?

你已经解决了这个问题。您可以找到它 "by eye",只需键入 "k" 并开始计数。或者您可以让 R 为您找到它。概率大于或等于.5的第一天是天数:

#TRUE is the maximum, pick the first of the ties:
which.max(k >= .5) 

我们可以从概率 .5 中找到绝对差值最小的那一天:

which.min(abs(k - .5))

"Birthday problem" 已经有两个 R 函数来解决它的各种形式:

birthday {stats}    R Documentation
Probability of coincidences

Description

Computes answers to a generalised birthday paradox problem. pbirthday computes the 
probability of a coincidence and qbirthday computes the smallest number of observations 
needed to have at least a specified probability of coincidence.

Usage

qbirthday(prob = 0.5, classes = 365, coincident = 2)
pbirthday(n, classes = 365, coincident = 2)

所以 `qbirthday:: 的默认值:

 > qbirthday()
 [1] 23