模拟 Alice 和 Bob 翻转相同数量的尾巴的概率

Simulating the probability that Alice and Bob flip the same number of tails

Alice tosses a fair coin n independent times and Bob tosses a fair coin m independent times. What is the probability that they have equal numbers of tails?

通过分析,概率给出为

(n+m选m) (1/2^(n+m))

例如,如果 n=5 且 m=7,则所需概率为

(5+7选7) (1/2^(5+7)) = 0.193

我有兴趣弄清楚如何在 R 中模拟这种情况。到目前为止,

coin=c("H","T")
n=5
m=7
u=replicate(10^6,sample(coin,n,repl=T))
v=replicate(10^6,sample(coin,m,repl=T))

但我不确定如何着手寻找给定样本中 u 和 v 的尾部数量相等的频率。

我尝试使用 table() 函数但是

table(u)
table(v)

只是 returns 每个样本中正面和反面的总和。

每个replication都存储在自己的uv的列中,所以需要统计每列的尾数并比较:

u_ntails = colSums(u == "T")
v_ntails = colSums(v == "T")

sum(u_ntails == v_ntails) / length(u_ntails)