-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprng.go
More file actions
53 lines (47 loc) · 1.02 KB
/
prng.go
File metadata and controls
53 lines (47 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package resrap
import (
"math/rand"
)
type prng struct {
seed uint64
number uint64
}
func (p *prng) setSeed(seed uint64) {
p.number = seed
p.seed = seed
}
func (p *prng) generateSeed() {
seed := rand.Uint64()
p.number = seed
p.seed = seed
}
func (p *prng) nextPRN() uint64 {
//Using the XOR shift method for PRN generation
p.number ^= p.number << 13
p.number ^= p.number >> 7
p.number ^= p.number << 17
return p.number
}
// random returns a float64 in [0,1)
func (p *prng) Random() float64 {
// Take the next 53 random bits (same precision as math/rand.Float64)
v := p.nextPRN() >> 11 // keep top 53 bits
return float64(v) / (1 << 53) // normalize to [0,1)
}
// randomInt returns an int in [min, max)
func (p *prng) RandomInt(min, max int) int {
if max <= min {
return min // avoid division by zero or negative range
}
r := p.Random()
return min + int(r*float64(max-min))
}
func newPRNG(seed uint64) prng {
prng := prng{}
if seed == 0 {
prng.generateSeed()
} else {
prng.setSeed(seed)
}
return prng
}