Added distribution test
This commit is contained in:
parent
d7c37b9060
commit
6c8e74bc5f
44
hash_test.go
44
hash_test.go
@ -2,6 +2,7 @@ package hash_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"math"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"git.akyoto.dev/go/hash"
|
"git.akyoto.dev/go/hash"
|
||||||
@ -57,3 +58,46 @@ func TestSameByte(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDistribution(t *testing.T) {
|
||||||
|
const (
|
||||||
|
maxSingleDiff = 0.03
|
||||||
|
maxAverageDiff = 0.01
|
||||||
|
)
|
||||||
|
|
||||||
|
totalDiff := 0.0
|
||||||
|
on := [64]int{}
|
||||||
|
off := [64]int{}
|
||||||
|
|
||||||
|
for sum := range hashes {
|
||||||
|
for bit := 0; bit < 64; bit++ {
|
||||||
|
if (sum & (1 << bit)) != 0 {
|
||||||
|
on[bit]++
|
||||||
|
} else {
|
||||||
|
off[bit]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for bit := 0; bit < 64; bit++ {
|
||||||
|
total := on[bit] + off[bit]
|
||||||
|
|
||||||
|
if total == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
probability := float64(on[bit]) / float64(total)
|
||||||
|
diff := probability - 0.5
|
||||||
|
totalDiff += math.Abs(diff)
|
||||||
|
|
||||||
|
if math.Abs(diff) > maxSingleDiff {
|
||||||
|
t.Logf("Bit %d: %.1f%% (should be closer to 50%%)", bit+1, probability*100)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
averageDiff := totalDiff / 64
|
||||||
|
|
||||||
|
if averageDiff > maxAverageDiff {
|
||||||
|
t.Fatalf("Average difference too high (> %.2f): %f", maxAverageDiff, averageDiff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user