Skip to content

Instantly share code, notes, and snippets.

@wch
Created February 16, 2024 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/5d0a461a2e222efa4a569d8cbb8d4f5a to your computer and use it in GitHub Desktop.
Save wch/5d0a461a2e222efa4a569d8cbb8d4f5a to your computer and use it in GitHub Desktop.
Calculate collision probabilities
# Calculate the probability of a collision if `n` items are randomly drawn (with
# replacement) from a set with `total` number of items.
collision_prob <- function(n, total) {
prob_no_collision <- 1
# Do this in a loop instead of prod(numerators)/prod(denominators), because
# that method is prone to result in a loss of precision due to rounding.
for (i in seq(0, n-1)) {
prob_no_collision <- prob_no_collision * (total - i) / total
}
1 - prob_no_collision
}
collision_prob(5, 9000)
#> [1] 0.001110679
collision_prob(5, 2^24)
#> [1] 5.960463e-07
collision_prob(12, 2^24)
#> [1] 3.9339e-06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment