Skip to content

Commit 08eaa09

Browse files
committed
Add false positives example
1 parent d68badd commit 08eaa09

1 file changed

Lines changed: 28 additions & 1 deletion

File tree

example_test.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@ package bloom_test
33
import (
44
"fmt"
55
"github.com/yourbasic/bloom"
6+
"math/rand"
7+
"strconv"
68
)
79

810
// Create and use a Bloom filter.
9-
func Example() {
11+
func Example_basics() {
1012
// Create a Bloom filter with room for 10000 elements
1113
// at a false-positives rate less than 0.5 percent.
1214
blacklist := bloom.New(10000, 200)
@@ -23,3 +25,28 @@ func Example() {
2325
}
2426
// Output: https://rascal.com seems to be shady.
2527
}
28+
29+
// Count the number of false positives.
30+
func Example_falsePositives() {
31+
// Create a Bloom filter with room for n elements
32+
// at a false-positives rate less than 1/p.
33+
n := 1000
34+
p := 100
35+
filter := bloom.New(n, p)
36+
37+
// Add n random strings.
38+
for i := 0; i < n; i++ {
39+
filter.Add(strconv.FormatUint(rand.Uint64(), 10))
40+
}
41+
42+
// Do n random lookups and count the (mostly accidental) hits.
43+
// It shouldn't be much more than n/p, and hopefully less.
44+
count := 0
45+
for i := 0; i < n; i++ {
46+
if filter.Test(strconv.FormatUint(rand.Uint64(), 10)) {
47+
count++
48+
}
49+
}
50+
fmt.Println(count, "mistakes were made.")
51+
// Output: 1 mistakes were made.
52+
}

0 commit comments

Comments
 (0)