math in bloom filter
A Bloom filter answers a narrow question: could this item be in a set? It trades occasional false positives for a compact representation. Here is how that tradeoff depends on the number of bits, items, and hashes.
Insertion and lookup
Start with an array of
- If any position is 0, the item is definitely absent.
- If every position is 1, the item may be present. Other inserted items could have set those bits.
The second answer is not a probability that the item belongs to the set; that would also depend on how likely our queries are to name members. A false-positive rate instead conditions on querying an item that was not inserted.
There are no false negatives as long as inserted bits remain set and insertion and lookup use the same hashes. Clearing a bit to delete one item can break this guarantee because another item may share that bit.
For the calculations below, assume
How likely is a bit to be set?
One hash misses a particular bit with probability
Consequently, its probability of being 1 is
Let
False positives: exact expression and approximation
If a particular filter has
Replacing the random occupancy by its mean gives the familiar approximation
The first replacement is not exact: different bit states are dependent. Since
For a small example, take
The mean-occupancy formula instead gives
A valid upper bound
A simple bound follows directly from occupancy. At most
Also,
These bounds are rigorous under the stated hash model, but can be loose. In the two-bit example they give
Choosing the number of hashes and bits
Write
This vanishes at
At this setting, about half the bits are set. Too few hashes leave useful space unused; too many fill the filter and make absent queries pass more often. Compare the positive integers on either side of
Substituting the optimum gives
For a target rate
For one million items and a 1% target, this suggests about 9.59 million bits, or 1.20 MB in decimal units, and 7 hashes. Using 9,585,059 bits and 7 hashes in the exponential formula gives about 1.004%; rounding the hash count means the sizing formula alone does not enforce the target. Ten million bits with 7 hashes gives an estimated 0.819% and some capacity margin.
The filter cannot grow its capacity merely by accepting more items. With ten million bits and 7 hashes, doubling the population to two million raises the same estimate to 13.8%. Plan for the expected distinct-item count, track occupancy, and verify positive answers against the underlying set when correctness requires an exact answer.