-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
rnd.go
383 lines (350 loc) · 9.05 KB
/
rnd.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Copyright (c) 2014 The mathutil Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mathutil
import (
"fmt"
"math"
"math/big"
)
// FC32 is a full cycle PRNG covering the 32 bit signed integer range.
// In contrast to full cycle generators shown at e.g. http://en.wikipedia.org/wiki/Full_cycle,
// this code doesn't produce values at constant delta (mod cycle length).
// The 32 bit limit is per this implementation, the algorithm used has no intrinsic limit on the cycle size.
// Properties include:
// - Adjustable limits on creation (hi, lo).
// - Positionable/randomly accessible (Pos, Seek).
// - Repeatable (deterministic).
// - Can run forward or backward (Next, Prev).
// - For a billion numbers cycle the Next/Prev PRN can be produced in cca 100-150ns.
// That's like 5-10 times slower compared to PRNs generated using the (non FC) rand package.
type FC32 struct {
cycle int64 // On average: 3 * delta / 2, (HQ: 2 * delta)
delta int64 // hi - lo
factors [][]int64 // This trades some space for hopefully a bit of speed (multiple adding vs multiplying).
lo int
mods []int // pos % set
pos int64 // Within cycle.
primes []int64 // Ordered. ∏ primes == cycle.
set []int64 // Reordered primes (magnitude order bases) according to seed.
}
// NewFC32 returns a newly created FC32 adjusted for the closed interval [lo, hi] or an Error if any.
// If hq == true then trade some generation time for improved (pseudo)randomness.
func NewFC32(lo, hi int, hq bool) (r *FC32, err error) {
if lo > hi {
return nil, fmt.Errorf("invalid range %d > %d", lo, hi)
}
if uint64(hi)-uint64(lo) > math.MaxUint32 {
return nil, fmt.Errorf("range out of int32 limits %d, %d", lo, hi)
}
delta := int64(hi) - int64(lo)
// Find the primorial covering whole delta
n, set, p := int64(1), []int64{}, uint32(2)
if hq {
p++
}
for {
set = append(set, int64(p))
n *= int64(p)
if n > delta {
break
}
p, _ = NextPrime(p)
}
// Adjust the set so n ∊ [delta, 2 * delta] (HQ: [delta, 3 * delta])
// while keeping the cardinality of the set (correlates with the statistic "randomness quality")
// at max, i.e. discard atmost one member.
i := -1 // no candidate prime
if n > 2*(delta+1) {
for j, p := range set {
q := n / p
if q < delta+1 {
break
}
i = j // mark the highest candidate prime set index
}
}
if i >= 0 { // shrink the inner cycle
n = n / set[i]
set = delete(set, i)
}
r = &FC32{
cycle: n,
delta: delta,
factors: make([][]int64, len(set)),
lo: lo,
mods: make([]int, len(set)),
primes: set,
}
r.Seed(1) // the default seed should be always non zero
return
}
// Cycle reports the length of the inner FCPRNG cycle.
// Cycle is atmost the double (HQ: triple) of the generator period (hi - lo + 1).
func (r *FC32) Cycle() int64 {
return r.cycle
}
// Next returns the first PRN after Pos.
func (r *FC32) Next() int {
return r.step(1)
}
// Pos reports the current position within the inner cycle.
func (r *FC32) Pos() int64 {
return r.pos
}
// Prev return the first PRN before Pos.
func (r *FC32) Prev() int {
return r.step(-1)
}
// Seed uses the provided seed value to initialize the generator to a deterministic state.
// A zero seed produces a "canonical" generator with worse randomness than for most non zero seeds.
// Still, the FC property holds for any seed value.
func (r *FC32) Seed(seed int64) {
u := uint64(seed)
r.set = mix(r.primes, &u)
n := int64(1)
for i, p := range r.set {
k := make([]int64, p)
v := int64(0)
for j := range k {
k[j] = v
v += n
}
n *= p
r.factors[i] = mix(k, &u)
}
}
// Seek sets Pos to |pos| % Cycle.
func (r *FC32) Seek(pos int64) { //vet:ignore
if pos < 0 {
pos = -pos
}
pos %= r.cycle
r.pos = pos
for i, p := range r.set {
r.mods[i] = int(pos % p)
}
}
func (r *FC32) step(dir int) int {
for { // avg loops per step: 3/2 (HQ: 2)
y := int64(0)
pos := r.pos
pos += int64(dir)
switch {
case pos < 0:
pos = r.cycle - 1
case pos >= r.cycle:
pos = 0
}
r.pos = pos
for i, mod := range r.mods {
mod += dir
p := int(r.set[i])
switch {
case mod < 0:
mod = p - 1
case mod >= p:
mod = 0
}
r.mods[i] = mod
y += r.factors[i][mod]
}
if y <= r.delta {
return int(y) + r.lo
}
}
}
func delete(set []int64, i int) (y []int64) {
for j, v := range set {
if j != i {
y = append(y, v)
}
}
return
}
func mix(set []int64, seed *uint64) (y []int64) {
for len(set) != 0 {
*seed = rol(*seed)
i := int(*seed % uint64(len(set)))
y = append(y, set[i])
set = delete(set, i)
}
return
}
func rol(u uint64) (y uint64) {
y = u << 1
if int64(u) < 0 {
y |= 1
}
return
}
// FCBig is a full cycle PRNG covering ranges outside of the int32 limits.
// For more info see the FC32 docs.
// Next/Prev PRN on a 1e15 cycle can be produced in about 2 µsec.
type FCBig struct {
cycle *big.Int // On average: 3 * delta / 2, (HQ: 2 * delta)
delta *big.Int // hi - lo
factors [][]*big.Int // This trades some space for hopefully a bit of speed (multiple adding vs multiplying).
lo *big.Int
mods []int // pos % set
pos *big.Int // Within cycle.
primes []int64 // Ordered. ∏ primes == cycle.
set []int64 // Reordered primes (magnitude order bases) according to seed.
}
// NewFCBig returns a newly created FCBig adjusted for the closed interval [lo, hi] or an Error if any.
// If hq == true then trade some generation time for improved (pseudo)randomness.
func NewFCBig(lo, hi *big.Int, hq bool) (r *FCBig, err error) {
if lo.Cmp(hi) > 0 {
return nil, fmt.Errorf("invalid range %d > %d", lo, hi)
}
delta := big.NewInt(0)
delta.Add(delta, hi).Sub(delta, lo)
// Find the primorial covering whole delta
n, set, pp, p := big.NewInt(1), []int64{}, big.NewInt(0), uint32(2)
if hq {
p++
}
for {
set = append(set, int64(p))
pp.SetInt64(int64(p))
n.Mul(n, pp)
if n.Cmp(delta) > 0 {
break
}
p, _ = NextPrime(p)
}
// Adjust the set so n ∊ [delta, 2 * delta] (HQ: [delta, 3 * delta])
// while keeping the cardinality of the set (correlates with the statistic "randomness quality")
// at max, i.e. discard atmost one member.
dd1 := big.NewInt(1)
dd1.Add(dd1, delta)
dd2 := big.NewInt(0)
dd2.Lsh(dd1, 1)
i := -1 // no candidate prime
if n.Cmp(dd2) > 0 {
q := big.NewInt(0)
for j, p := range set {
pp.SetInt64(p)
q.Set(n)
q.Div(q, pp)
if q.Cmp(dd1) < 0 {
break
}
i = j // mark the highest candidate prime set index
}
}
if i >= 0 { // shrink the inner cycle
pp.SetInt64(set[i])
n.Div(n, pp)
set = delete(set, i)
}
r = &FCBig{
cycle: n,
delta: delta,
factors: make([][]*big.Int, len(set)),
lo: lo,
mods: make([]int, len(set)),
pos: big.NewInt(0),
primes: set,
}
r.Seed(1) // the default seed should be always non zero
return
}
// Cycle reports the length of the inner FCPRNG cycle.
// Cycle is atmost the double (HQ: triple) of the generator period (hi - lo + 1).
func (r *FCBig) Cycle() *big.Int {
return r.cycle
}
// Next returns the first PRN after Pos.
func (r *FCBig) Next() *big.Int {
return r.step(1)
}
// Pos reports the current position within the inner cycle.
func (r *FCBig) Pos() *big.Int {
return r.pos
}
// Prev return the first PRN before Pos.
func (r *FCBig) Prev() *big.Int {
return r.step(-1)
}
// Seed uses the provided seed value to initialize the generator to a deterministic state.
// A zero seed produces a "canonical" generator with worse randomness than for most non zero seeds.
// Still, the FC property holds for any seed value.
func (r *FCBig) Seed(seed int64) {
u := uint64(seed)
r.set = mix(r.primes, &u)
n := big.NewInt(1)
v := big.NewInt(0)
pp := big.NewInt(0)
for i, p := range r.set {
k := make([]*big.Int, p)
v.SetInt64(0)
for j := range k {
k[j] = big.NewInt(0)
k[j].Set(v)
v.Add(v, n)
}
pp.SetInt64(p)
n.Mul(n, pp)
r.factors[i] = mixBig(k, &u)
}
}
// Seek sets Pos to |pos| % Cycle.
func (r *FCBig) Seek(pos *big.Int) {
r.pos.Set(pos)
r.pos.Abs(r.pos)
r.pos.Mod(r.pos, r.cycle)
mod := big.NewInt(0)
pp := big.NewInt(0)
for i, p := range r.set {
pp.SetInt64(p)
r.mods[i] = int(mod.Mod(r.pos, pp).Int64())
}
}
func (r *FCBig) step(dir int) (y *big.Int) {
y = big.NewInt(0)
d := big.NewInt(int64(dir))
for { // avg loops per step: 3/2 (HQ: 2)
r.pos.Add(r.pos, d)
switch {
case r.pos.Sign() < 0:
r.pos.Add(r.pos, r.cycle)
case r.pos.Cmp(r.cycle) >= 0:
r.pos.SetInt64(0)
}
for i, mod := range r.mods {
mod += dir
p := int(r.set[i])
switch {
case mod < 0:
mod = p - 1
case mod >= p:
mod = 0
}
r.mods[i] = mod
y.Add(y, r.factors[i][mod])
}
if y.Cmp(r.delta) <= 0 {
y.Add(y, r.lo)
return
}
y.SetInt64(0)
}
}
func deleteBig(set []*big.Int, i int) (y []*big.Int) {
for j, v := range set {
if j != i {
y = append(y, v)
}
}
return
}
func mixBig(set []*big.Int, seed *uint64) (y []*big.Int) {
for len(set) != 0 {
*seed = rol(*seed)
i := int(*seed % uint64(len(set)))
y = append(y, set[i])
set = deleteBig(set, i)
}
return
}