From 443b62481d18eedf591c41773667909bc0520e0d Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Tue, 13 May 2014 13:06:48 +0200 Subject: [PATCH] BloomFilter: set a lower bound on nHashFuncs of 1: there must always be at least one function. Thanks to Kalpesh Parmar for debugging this. Static import Math for shorter more readable code. --- .../java/com/google/bitcoin/core/BloomFilter.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/com/google/bitcoin/core/BloomFilter.java b/core/src/main/java/com/google/bitcoin/core/BloomFilter.java index 03373a17..8e619d8b 100644 --- a/core/src/main/java/com/google/bitcoin/core/BloomFilter.java +++ b/core/src/main/java/com/google/bitcoin/core/BloomFilter.java @@ -23,6 +23,7 @@ import java.io.OutputStream; import java.util.Arrays; import static com.google.common.base.Preconditions.checkArgument; +import static java.lang.Math.*; /** *

A Bloom filter is a probabilistic data structure which can be sent to another client so that it can avoid @@ -101,11 +102,12 @@ public class BloomFilter extends Message { 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()); } @@ -114,7 +116,7 @@ public class BloomFilter extends Message { * 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