Skip to content

Instantly share code, notes, and snippets.

@revodavid
Last active January 24, 2018 23:39
Show Gist options
  • Select an option

  • Save revodavid/ab174e1e2077187244d7b49afdd04204 to your computer and use it in GitHub Desktop.

Select an option

Save revodavid/ab174e1e2077187244d7b49afdd04204 to your computer and use it in GitHub Desktop.
R function to simulate the Birthday paradox
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