Last active
January 24, 2018 23:39
-
-
Save revodavid/ab174e1e2077187244d7b49afdd04204 to your computer and use it in GitHub Desktop.
R function to simulate the Birthday paradox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pbirthdaysim <- function(n, nsims=100000, feb29=TRUE) { | |
| ## Using nsims simulations, estimate the probability | |
| ## that a room of n people includes a shared birthday | |
| bdays <- 1:366 | |
| ## Feb 29 represented as day 366 | |
| ## We'll sample other days 4 times as often | |
| ## compared to day 366 | |
| probs <- c(rep(4,365),1) | |
| if(!feb29) { | |
| # drop Feb 29 from bdays and probs | |
| bdays <- bdays[-366] | |
| probs <- probs[-366] | |
| } | |
| probs <- probs/sum(probs) | |
| anydup <- function(ignored) | |
| ## simulate n birthdays, return TRUE if | |
| ## there's a duplicate | |
| any(duplicated( | |
| sample(bdays, n, prob=probs, replace=TRUE))) | |
| sum(sapply(seq(nsims), anydup)) / nsims | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment