Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introducing a faster bounded RNG: #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions pcg32.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,24 @@ func (p *PCG32) Bounded(bound uint32) uint32 {
}
}

// as in int31n, go/src/math/rand/rand.go
// this function uses a single division in the worst case
func (p *PCG32) FastBounded(bound uint32) uint32 {
v := p.Random()
prod := uint64(v) * uint64(bound)
low := uint32(prod)
if low < uint32(bound) {
thresh := uint32(-bound) % uint32(bound)
for low < thresh {
v = p.Random()
prod = uint64(v) * uint64(bound)
low = uint32(prod)
}
}
return uint32(prod >> 32)
}


func (p *PCG32) Advance(delta uint64) *PCG32 {
p.state = p.advanceLCG64(p.state, delta, pcg32Multiplier, p.increment)
return p
Expand Down
13 changes: 13 additions & 0 deletions pcg32_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,19 @@ func BenchmarkBounded32(b *testing.B) {
// _ = pcg.Bounded(365) // day of year
}
}
// Measure the time it takes to generate bounded random values
func BenchmarkBounded32Fast(b *testing.B) {
b.StopTimer()
pcg := NewPCG32().Seed(1, 1)
b.StartTimer()

for i := 0; i < b.N; i++ {
_ = pcg.FastBounded(uint32(i) & 0xff) // 0..255
// _ = pcg.Bounded(6) // roll of die
// _ = pcg.Bounded(52) // deck of cards
// _ = pcg.Bounded(365) // day of year
}
}

//
// EXAMPLES
Expand Down