Skip to content

Commit

Permalink
BloomFilter: set a lower bound on nHashFuncs of 1: there must always …
Browse files Browse the repository at this point in the history
…be at least one function. Thanks to Kalpesh Parmar for debugging this.

Static import Math for shorter more readable code.
  • Loading branch information
mikehearn committed May 13, 2014
1 parent cbd91c7 commit 443b624
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions core/src/main/java/com/google/bitcoin/core/BloomFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.Arrays;

import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.Math.*;

/**
* <p>A Bloom filter is a probabilistic data structure which can be sent to another client so that it can avoid
Expand Down Expand Up @@ -101,11 +102,12 @@ public BloomFilter(int elements, double falsePositiveRate, long randomNonce) {
public BloomFilter(int elements, double falsePositiveRate, long randomNonce, BloomUpdate updateFlag) {
// The following formulas were stolen from Wikipedia's page on Bloom Filters (with the addition of min(..., MAX_...))
// Size required for a given number of elements and false-positive rate
int size = Math.min((int)(-1 / (Math.pow(Math.log(2), 2)) * elements * Math.log(falsePositiveRate)),
(int)MAX_FILTER_SIZE * 8) / 8;
data = new byte[size <= 0 ? 1 : size];
int size = (int)(-1 / (pow(log(2), 2)) * elements * log(falsePositiveRate));
size = max(1, min(size, (int) MAX_FILTER_SIZE * 8) / 8);
data = new byte[size];
// Optimal number of hash functions for a given filter size and element count.
hashFuncs = Math.min((int)(data.length * 8 / (double)elements * Math.log(2)), MAX_HASH_FUNCS);
hashFuncs = (int)(data.length * 8 / (double)elements * log(2));
hashFuncs = max(1, min(hashFuncs, MAX_HASH_FUNCS));
this.nTweak = randomNonce;
this.nFlags = (byte)(0xff & updateFlag.ordinal());
}
Expand All @@ -114,7 +116,7 @@ public BloomFilter(int elements, double falsePositiveRate, long randomNonce, Blo
* Returns the theoretical false positive rate of this filter if were to contain the given number of elements.
*/
public double getFalsePositiveRate(int elements) {
return Math.pow(1 - Math.pow(Math.E, -1.0 * (hashFuncs * elements) / (data.length * 8)), hashFuncs);
return pow(1 - pow(E, -1.0 * (hashFuncs * elements) / (data.length * 8)), hashFuncs);
}

@Override
Expand Down

0 comments on commit 443b624

Please sign in to comment.