## Estimate the probability that at least two people in a group of 30 ## people have the same birthday. ## ## Assume that there are 365 days in every year, and that birthdays are ## independent and equally likely to occur on any day. ## The number of simulation replications. nrep = 1e4 ## The number of individuals in the group. nsub = 30 ## The number of simulations with at least one common birthday. n1 = 0 ## Simulation loop. for (i in 1:nrep) { ## Generate the birthdays. bday = ceiling(runif(min=0, max=365, n=nsub)) ## The unique birthdays. ubday = unique(bday) ## Check whether there were any shared birthdays. if (length(ubday) < nsub) { n1 = n1+1 } } ## The estimated probability of a shared birthday. p_est = n1 / nrep ## The exact probability. The probability that all birthdays are different is: ## ## P(2nd bday is different from 1st) * P(3rd bday is different from first 2) ## * ... * P(nsub^th bday is different from all others) ## ## We take 1 minus this to get the probability we want. p_exact = 1 for (k in 1:(nsub-1)) { p_exact = p_exact * (1 - k/365) } p_exact = 1 - p_exact ## A numerical approximation to the exact probability. p_approx = 1 - exp(-nsub*(nsub-1)/730)