From 6c8e74bc5ffe73fc248bde734574d30c7d68ad38 Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Sun, 23 Jul 2023 20:58:26 +0200 Subject: [PATCH] Added distribution test --- hash_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/hash_test.go b/hash_test.go index db98e6d..efaf632 100644 --- a/hash_test.go +++ b/hash_test.go @@ -2,6 +2,7 @@ package hash_test import ( "bytes" + "math" "testing" "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) + } +}