Created
February 16, 2024 14:35
-
-
Save wch/5d0a461a2e222efa4a569d8cbb8d4f5a to your computer and use it in GitHub Desktop.
Calculate collision probabilities
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
# 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