-
Notifications
You must be signed in to change notification settings - Fork 29
/
random.go
55 lines (49 loc) · 964 Bytes
/
random.go
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
54
55
package random
/*
* Interface type for a pseudo random number generator.
*/
type PseudoRandomNumberGenerator interface {
NextFloat() float64
}
/*
* Data structure representing a linear congruency generator.
*/
type linearCongruencyGenerator struct {
a uint64
b uint64
n uint64
x uint64
}
/*
* Samples a new random number in the interval [0, 1] from a uniform distribution.
*/
func (this *linearCongruencyGenerator) NextFloat() float64 {
a := this.a
b := this.b
n := this.n
x := this.x
x = ((a * x) + b) % n
this.x = x
xFloat := float64(x)
xMax := n - 1
xMaxFloat := float64(xMax)
result := xFloat / xMaxFloat
return result
}
/*
* Creates a new pseudo random number generator.
*/
func CreatePRNG(seed uint64) PseudoRandomNumberGenerator {
n := uint64((1 << 31) - 1)
x := ((64979 * seed) + 83) % n
/*
* Initialize a new LCG.
*/
generator := linearCongruencyGenerator{
a: 16807,
b: 0,
n: n,
x: x,
}
return &generator
}