Biased random generator
This commit is contained in:
10
gen/rand.go
Normal file
10
gen/rand.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package gen
|
||||||
|
|
||||||
|
import "math/rand"
|
||||||
|
|
||||||
|
// Generate a random uint64 with an even distribution of bits.Len64()
|
||||||
|
func RandBiasedUint64() uint64 {
|
||||||
|
// The shift-right by up to 64 (shifting it to 0) makes up for randomness
|
||||||
|
// lost by setting the high bit.
|
||||||
|
return (rand.Uint64() | 0x8000000000000000) >> rand.Int31n(65)
|
||||||
|
}
|
||||||
33
test/rand_test.go
Normal file
33
test/rand_test.go
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import "math"
|
||||||
|
import "math/bits"
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
import "github.com/firestuff/subcoding/gen"
|
||||||
|
|
||||||
|
func TestRandBiasedUint64(t *testing.T) {
|
||||||
|
buckets := [65]uint64{}
|
||||||
|
|
||||||
|
for i := 0; i < 1000000; i++ {
|
||||||
|
val := gen.RandBiasedUint64()
|
||||||
|
buckets[bits.Len64(val)]++
|
||||||
|
}
|
||||||
|
|
||||||
|
var max uint64 = 0
|
||||||
|
var min uint64 = math.MaxUint64
|
||||||
|
|
||||||
|
for _, count := range buckets {
|
||||||
|
if count > max {
|
||||||
|
max = count
|
||||||
|
}
|
||||||
|
|
||||||
|
if count < min {
|
||||||
|
min = count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if max - min > max / 10 {
|
||||||
|
t.Fatalf("Variance greater than allowed: %d > %d (max=%d min=%d)", max - min, max / 10, max, min)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user