-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmersenne_twister.go
55 lines (49 loc) · 1.02 KB
/
mersenne_twister.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 MersenneTwister
import(
"sync"
)
type Generator struct{
state [624]uint32
index uint32
generating sync.Mutex
}
func Init(a uint32) *Generator{
var t Generator
t.init(a)
return &t
}
func (g *Generator) init(a uint32){
g.generating.Lock()
g.state[0] = a
var i uint32 = 0
for i=1; i<624; i++{
g.state[i] = uint32(0x6c078965 * (g.state[i-1] ^
g.state[i-1]>>30) + i)
}
g.generating.Unlock()
}
func (g *Generator) Next() uint32{
g.generating.Lock()
if g.index == 0{
g.generateNumbers()
}
y := g.state[g.index]
g.index++
g.index %= 624
g.generating.Unlock()
y ^= y>>11
y ^= y<<7 & 0x9d2c5680
y ^= y<<15 & 0xefc60000
y ^= y>>18
return y
}
func (g *Generator) generateNumbers(){
var i uint32
for i=0; i<624; i++{
y := g.state[i]>>31 + g.state[(i+1)%624] & 0x7fffffff
g.state[i] = g.state[(i+397)%624] ^ y>>1
if y%2 == 1{
g.state[i] ^= 0x9908b0df
}
}
}