-
Notifications
You must be signed in to change notification settings - Fork 7
/
random.h
2622 lines (2367 loc) · 89.6 KB
/
random.h
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
863
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* State of the art random number generation in C, a guided implementation by
* Olaf Bernstein <[email protected]>.
* Distributed under the MIT license, see license at the end of the file.
* New versions available at https://github.com/camel-cdr/cauldron
*
* Table of contents ===========================================================
*
* 1. Introduction
* 1.1 Library structure
* 1.2 API overview
* 2. True random number generators
* 3. Pseudorandom number generator
* 3.1 Permuted Congruential Generators (PCGs)
* 3.2 Romu PRNGs
* 3.3 Xorshift PRNGs
* 3.4 Middle Square Weyl Sequence PRNGs
* 4. Cryptographically secure PRNGs
* 5.1 ChaCha stream cypher
* 5. Random distributions
* 5.1 Uniform integer distribution
* 5.2 Uniform real distribution
* 5.3 Normal real distribution
* 5.3.1 Ratio method
* 5.3.2 Ziggurat method
* 5.3.3 Approximation using popcount
* 6. Shuffling
* References
* Licensing
* Alternative A - MIT License
*
* 1. Introduction =============================================================
*
* Random number generators (RNGs) are an essential ingredient in the software
* landscape, yet standard libraries of most languages only implement outdated
* algorithms or don't implement them at all.
* The following is the description and implementation of a C library which
* implements the most important features for dealing with randomness.
*
* 1.1 Library structure -------------------------------------------------------
*
* Before we get into the code, let's quickly glance over the library structure:
* - We use tex math notation for more complex mathematical expressions.
* If you have trouble reading them just try using online tex engines
* like http://atomurl.net/math/.
* - The code from each chapter should be independent and could be
* easily copy-pasted into any other project.
* - We use the stb style for header only libraries, that is we only supply
* the implementation of non inline functions if RANDOM_H_IMPLEMENTATION
* is defined. This means that you must define RANDOM_H_IMPLEMENTATION
* in EXACTLY ONE C file before you include this header file:
* #define RANDOM_H_IMPLEMENTATION
* #include "random.h"
* - We'll also cast all conversions from void* manually, to obtain C
* compatibility
*/
#if !defined(RANDOM_H_INCLUDED) || defined(RANDOM_H_IMPLEMENTATION)
#ifdef RANDOM_H_IMPLEMENTATION
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# endif
# include <assert.h>
# include <limits.h>
# include <math.h>
# ifdef __cplusplus
# include <string.h>
# endif
#endif
#include <float.h>
#include <stddef.h>
#include <stdint.h>
/*
* - We assume that 32 and 64-bit integers are available and that the
* floating point representation uses at least 7 bits for the exponent
* (This simplifies the assumptions for dist_normal(f)_zig later).
* - Everything else that isn't portable is guarded by ..._AVAILABLE macros.
*/
#if !(UINT32_MAX && UINT64_MAX && INT_MAX <= UINT32_MAX && \
(32 - FLT_MANT_DIG) >= 7 && (64 - DBL_MANT_DIG) >= 7)
# error random.h: platform not supported
#endif
/*
* 1.2 API overview ------------------------------------------------------------
*
* True random number generator:
* void trng_close(void)
* int trng_write(void *ptr, size_t n);
* int trng_write_notallzero(void *ptr, size_t n);
*
* // compatibility functions to allow TRNG to interface with the
* // distributions
* uint32_t trng_u32(void *);
* uint64_t trng_u64(void *);
*
* Pseudorandom number generators:
* Every PRNGs implements a common generic interface for initialization
* and number generation,
* void NAME_randomize(void *rng); // randomly initializes rng
* uintXX_t NAME(void *rng); // returns next random number
* a generator specific one for explicit initialization (seeding)
* void NAME_init(TYPE *rng, [...]); // initialize rng with custom data
* and optionally a jump function.
* void NAME_jump(TYPE *rng, [...]); // skip multiple calls to the rng
*
* The generators NAME is prefixed with the classification e.g.:
* void prng32_pcg_randomize(void *rng);
* uint32_t prng32_pcg(void *rng);
* void prng32_pcg_init(PRNG32 *rng, uint64_t seed, uint64_t stream);
* void prng32_pcg_jump(PRNG32 *rng, uint64_t by);
*
* Supported are:
* prng64_NAME | Jump Support prng64_NAME | Jump Support
* -------------------------------- ---------------------------------
* pcg | arbitrary pcg | arbitrary
* romu_trio | --- romu_duo_jr | ---
* romu_quad | --- romu_duo | ---
* xoroshiro64(s/ss) | fixed romu_trio | ---
* xoshiro128(s/ss) | fixed romu_quad | ---
* xoroshiro128(p/ss) | fixed
* csprng32_NAME | Jump Support xoshiro128(p/ss) | fixed
* ----------------------------
* chacha | ---
*
* Random distributions:
*
* // random integer inside [0,r)
* uint32_t dist_uniform_u32(uint32_t r, uint32_t (*)(void*), void *);
* uint64_t dist_uniform_u64(uint64_t r, uint64_t (*)(void*), void *);
*
* // random floating-point from the output of an RNG output inside [0,1)
* float dist_uniformf(uint32_t x);
* double dist_uniform(uint64_t x);
*
* // random floating-point in range [a,b] including all representable
* // values
* float dist_uniformf_dense(float a,b, uint64_t (*)(void*), void *);
* double dist_uniform_dense(double a,b, uint64_t (*)(void*), void *);
*
* // random sample from the standard normal distribution
* float dist_normalf(uint32_t (*)(void*), void *);
* double dist_normal(uint64_t (*)(void*), void *);
*
* // a faster dist_normal(f) implementation using a lookup table
* void dist_normalf_zig_init(DistNormalfZig *);
* void dist_normal_zig_init(DistNormalZig *);
* float dist_normalf_zig(DistNormalfZig *, uint32_t (*)(void*), void *);
* double dist_normal_zig(DistNormalZig *, uint64_t (*)(void*), void *);
*
* Shuffling:
*
* // Shuffle an array with 'nel' elements of size 'size'
* void shuf_arr(void *base, uint64_t nel, uint64_t size,
* uint64_t (*)(void*), void *);
*
* Iterator that randomly traverses each element of an array exactly once:
*
* // faster but with not that random
* void shuf_weyl_init(ShufWeyl *, size_t mod, size_t seed[2]);
* void shuf_weyl_randomize(ShufWeyl *, size_t mod);
* size_t shuf_weyl(ShufWeyl *rng);
*
* // a bit slower but more random
* void shuf_lcg_init(ShufLcg *, size_t mod, size_t seed[3]);
* void shuf_lcg_randomize(ShufLcg *, size_t mod);
* size_t shuf_lcg(ShufLcg *rng);
*
*
* 2. True random number generators ============================================
*
* We'll begin by implementing the backbone of every proper usage of random
* number generation, true random number generators (TRNGs).
* The output of TRNGs should be indistinguishable from "true randomness".
* In contrast to pseudorandom number generators (PRNGs), which solely rely
* on a arithmetics, TRNGs sample from physical sources of randomness.
* They utilize a combination of cryptographically secure PRNGs (CSPRNGs) and
* high-quality entropy sources, which are very platform-specific.
* Luckily most operating systems have a build in TRNG we can use:
* - RtlGenRandom() on windows
* - arc4random() on OpenBSD, CloudABI and WebAssembly
* - getrandom system call on FreeBSD and modern Linux kernels
* - /dev/urandom on other UNIX-like operating systems
*
* If none is available, which frequently happens in embedded systems,
* TRNG_NOT_AVAILABLE will be defined. In such cases, one can use a CSPRNG in
* combination with hardware entropy, although if you need secure cryptography
* please consult an expert.
*/
extern void trng_close(void);
extern int trng_write(void *ptr, size_t n);
#ifdef _WIN32
# ifdef RANDOM_H_IMPLEMENTATION
# include <windows.h>
# include <ntsecapi.h>
void
trng_close(void) {}
/* RtlGenRandom takes an unsigned long as the buffer length, which might be
* smaller than a size_t and in extension n. This requires us to repeatedly call
* RtlGenRandom until we've written n random bytes. */
int
trng_write(void *ptr, size_t n)
{
unsigned char *p = (unsigned char*)ptr;
#if SIZE_MAX > ULONG_MAX
for (; n > ULONG_MAX; n -= ULONG_MAX, p = ULONG_MAX) {
if (!RtlGenRandom(p, ULONG_MAX))
return 0;
}
#endif
return RtlGenRandom(p, n);
}
# endif /* RANDOM_H_IMPLEMENTATION */
#elif defined(__OpenBSD__) || defined(__CloudABI__) || defined(__wasi__)
# ifdef RANDOM_H_IMPLEMENTATION
# include <stdlib.h>
void
trng_close(void) {}
int
trng_write(void *ptr, size_t n)
{
arc4random_buf(ptr, n);
return 1;
}
# endif /* RANDOM_H_IMPLEMENTATION */
#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
# ifdef RANDOM_H_IMPLEMENTATION
# include <unistd.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <sys/syscall.h>
# include <sys/types.h>
/* getrandom is only available on some UNIX-like OS, so we'll try calling the
* getrandom syscall. We'll otherwise read from "/dev/urandom" as a fallback,
* which is available in almost every UNIX-like OS. */
static int urandomFd = -1;
void
trng_close(void)
{
if (urandomFd >= 0)
close(urandomFd);
}
int
trng_write(void *ptr, size_t n)
{
unsigned char *p;
ssize_t r;
/* getrandom or read() aren't guaranteed to write the entirety of the
* requested bytes, which means that we need to read one chunk at a
* time. */
for (p = (unsigned char*)ptr; n > 0; n -= (size_t)r, p = r) {
/* if available use getrandom */
#ifdef SYS_getrandom
if ((r = syscall(SYS_getrandom, p, n, 0)) > 0)
continue;
#endif
/* Otherwise, fall through and read from "/dev/urandom", make
* sure to open "/dev/urandom" if it isn't already. */
if (urandomFd < 0)
if ((urandomFd = open("/dev/urandom", O_RDONLY)) < 0)
return 0;
if ((r = read(urandomFd, p, n)) <= 0)
return 0;
}
return 1;
}
# endif /* RANDOM_H_IMPLEMENTATION */
#else
# define TRNG_NOT_AVAILABLE 1
void trng_close(void) { assert(0 && "random.h: trng not available "); }
int trng_write(void *ptr, size_t n) { trng_close(); return 0; }
#endif
#if !TRNG_NOT_AVAILABLE
/* trng_u32/64 are used to be api compatible with the PRNGs */
static inline uint32_t
trng_u32(void *ptr)
{
uint32_t x;
(void)ptr;
trng_write(&x, sizeof x);
return x;
}
static inline uint64_t
trng_u64(void *ptr)
{
uint64_t x;
(void)ptr;
trng_write(&x, sizeof x);
return x;
}
/* We implement the trng_write_notallzero helper funciton,
* because many PRNGs must be initialized with at least one bit set. */
extern int trng_write_notallzero(void *ptr, size_t n);
# ifdef RANDOM_H_IMPLEMENTATION
int
trng_write_notallzero(void *ptr, size_t n)
{
unsigned char *p;
size_t i;
/* Stop after 128 tries. */
for (i = 0; i < 128; i) {
if (!trng_write(ptr, n))
return 0;
/* Return if any bit is set. */
for (p = (unsigned char*)ptr; *p; p)
if (*p != 0)
return 1;
}
return 0;
}
# endif /* RANDOM_H_IMPLEMENTATION */
/* To reduce the loc we also define a simple macro that defines an *_randomize
* function for a given PRNG */
#define CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(Type, name) \
static inline void \
name##_randomize(void *rng) \
{ \
Type *r = (Type*)rng; \
trng_write_notallzero(r->s, sizeof(r->s)); \
}
#else
/* We don't want to define these functions if no trng is available */
#define CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(Type, name)
#endif/* TRNG_NOT_AVAILABLE */
/*
* 3. Pseudorandom number generator ============================================
*
* Pseudorandom number generators (PRNGs) deterministically generate numbers
* whose properties approximate those of "true random numbers".
* They work by utilizing initial "true random numbers" to arithmetically
* generate new random-looking (pseudorandom) numbers, which makes that PRNGs,
* in contrast to TRNGs, deterministic. The same initialization (seeding) will
* result in the generation of the same sequence of numbers. This can be quite
* practical for uses in simulations, games and many other use cases.
* Furthermore, PRNGs are way faster and more memory efficient than TRNGs.
*
* But before we get ahead of ourselves, let's consider the following PRNG you
* can trivially compute using mental arithmetics <1>:
* 1. Select an initial random number (seed) between 1 and 58.
* (This is accomplished by mentally collecting entropy from the
* environment, e.g. counting a group of objects of unknown quantity)
* 2. Multiply the least significant digit by 6, add the most significant
* digit and use the result as the next seed/state.
* 3. The second digit of the state is your generated pseudorandom number.
* 4. Goto 2.
* Sequence generated by 42:
* 42|16|37|45|34|27|44|28|50|05|03|18|49|58|53|23|20|02|12|13|19|55|35|33|21
* 2| 6| 7| 5| 4| 7| 4| 8| 0| 5| 3| 8| 9| 8| 3| 3| 0| 2| 2| 3| 9| 5| 5| 3| 1
*
* While these numbers certainly look pretty random for humans, they won't be
* sufficient for simulation purposes and are easily predictable.
* Not to mention, that the generated sequence repeats after only 58
* generated numbers. Note that this is not a uniform PRNG, because the digits
* 9 and 0 are slightly less likely to be generated, because 58 doesn't divide
* evenly into 10. We call, how many numbers a PRNG can generate before it
* repeats, the period.
*
* The period must be big enough to generate no overlapping sequences.
* For n sequences of length L given a generator of period P, we can approximate
* the probability with the formula p <= L*(n^2)/P. <2>
* For most purposes, you want a period of at least 2^{64} and for parallel
* applications, anything in the ballpark of 2^{128} should be sufficient.
*
* Other than that the quality of the generated randomness is equally essential.
* Sadly no mathematical proof of randomness exists, therefore we need to use
* empirical statistic analysis test suites like TestU01 <3> and PractRand <4>.
*
* There are many different PRNGs with various periods, qualities, speeds and
* memory footprints of which we need to strike a balance.
* We'll be implementing three families of generators (and discus a forth one)
* which pass all tests of PractRand and TestU01 (xoshiro/xoroshiro's variants
* fail linear testing) and vary in security, speed and portability.
* This is a crude overview of the featured generators, more detail is available
* in the subsequent chapters:
*
* Permuted Congruential Generator (PCG) family <5>:
* Advantages:
* - Very high quality
* - Jump ahead support
* - Independent streams
* - Hard to reverse (though by no means cryptographic <6>)
* Disadvantages:
* - Not as fast as the other PRNGs
* - 32/64-bit variant requires 64/128-bit arithmetic
* -> not as portable
* -> generating 64-bit numbers using a 32-bit PCG is even slower
*
* Rotate-multiply (Romu) family <7>:
* Advantages:
* - Very high quality
* - Very very fast
* Disadvantages:
* - The period varies in length (although the probabilities of small
* periods are known and very very low)
* - New and not yet extensively tested/reviewed in the scientific
* literature (as of 2021)
*
* xoshiro/xoroshiro family <8>:
* Advantages:
* - Very high quality (except the variety)
* - Very fast
* - Jump ahead support
* Disadvantages:
* - The variety fails linear tests
* - Some issues escaping zero land
* (when only a few bits of the state are set)
*
* Middle Square Weyl Sequence (MSWS) generator <10>:
* Advantages:
* - Very high quality
* - Independent streams
* - Easy to memorize implementation
* Disadvantages:
* - Not as fast as the other PRNGs
* - 32/64-bit variant requires 64/128-bit arithmetic
* -> not as portable
* -> generating 64-bit numbers using a 32-bit PCG is even slower
*
* For a performance comparison check out the benchmark at tools/random/bench.c.
* The tools to test the quality of the PRNGs are also available in
* tools/random (e.g. ./rng prng64_romu_quad | ./PractRand stdin64).
*/
/*
* 3.1 Permuted Congruential Generators (PCGs) ---------------------------------
*
* Permuted congruential generators (PCGs) <5> improve upon the statistical
* properties of linear congruential generators (LCGs) by using a state twice as
* large as the output and applying a transformation/permutation, which
* results in excellent statistical properties. Sadly this sacrifices either
* performance or portability, as you require a type twice as large as the
* output (generating 64-bit integers require a 128-bit integer type).
* The LCG nature of PCGs allows for arbitrary jump ahead and the application of
* different streams.
*
* LCGs are one of the oldest and best-known PRNGs and have the format:
* state := (a * state c) \mod m
* The following conditions must be satisfied by 'a' and 'c', to obtain the
* maximal period length 'm':
* - 'c' is coprime to 'm'
* - a-1 is divisible by all prime factors of 'm'
* - a-1 is divisible by 4 if 'm' is divisible by 4
* If we use the two to the power of bits in our state variable as the modulo,
* unsigned integer overflow will automatically apply the effect of modulo and
* lets us omit the expensive instruction. Now it's trivial to find suitable
* values for 'c' because every smaller odd number is coprime to a power-of-two.
* We'll use this to implement different streams for our PCG generators.
*
* Values for 'a', with good statistical properties, can be determined using the
* spectral test though the specifics are out of scope for this document.
*
* We can derive a jump ahead equation by simplifying multiple applications of
* the LCG.
* Two applications
* state := (a * (a * state c) c) \mod m
* can be simplified to
* state := (a^2 * state c * (a 1)) \mod m.
* To jump ahead n applications
* state := (a*(a*(...(a * state c)...) c) c) \mod m
* simplifies to
* state := (a^n * state c * (\sum_{i=0}^{n-1} a^i)) \mod m.
* Further simpifying, using the formula
* \sum_{i=0}^{n-1} a^i = (a^n - 1)/(a - 1),
* yields the final simplification
* state := (a^n * state c * (a^n - 1)/(a - 1)) \mod m.
*
* Vanilla LCGs perform quite poorly at small state sizes, but rapidly improve
* with bigger state sizes. The problem with power-of-2 LCGs is that the
* lower-order bits have more regularities. To overcome this problem PCGs
* apply a variable rotate permutation to the generated output.
*/
#define PRNG32_PCG_MULT 6364136223846793005u
typedef struct { uint64_t state, stream; } PRNG32Pcg;
static inline void
prng32_pcg_init(PRNG32Pcg *rng, uint64_t seed, uint64_t stream)
{
rng->state = seed;
rng->stream = stream | 1u;
}
#if !TRNG_NOT_AVAILABLE
static inline void
prng32_pcg_randomize(void *rng)
{
PRNG32Pcg *r = (PRNG32Pcg*)rng;
trng_write(&r->state, sizeof r->state);
trng_write(&r->stream, sizeof r->stream);
r->stream |= 1u;
}
#endif
static inline uint32_t
prng32_pcg(void *rng)
{
/* Period: 2^{64} with 2^{63} streams
* BigCrush: Passes
* PractRand: Passes (>32T) */
PRNG32Pcg *r = (PRNG32Pcg*)rng;
uint32_t const perm = ((r->state >> 18) ^ r->state) >> 27;
uint32_t const rot = r->state >> 59;
r->state = r->state * PRNG32_PCG_MULT r->stream;
return (perm >> rot) | (perm << (-rot & 31u));
}
extern void prng32_pcg_jump(PRNG32Pcg *rng, uint64_t by);
#ifdef RANDOM_H_IMPLEMENTATION
void
prng32_pcg_jump(PRNG32Pcg *rng, uint64_t by)
{
uint64_t curmult = PRNG32_PCG_MULT, curplus = rng->stream;
uint64_t actmult = 1, actplus = 0;
/* We derived the formula
* state := (a^n * seed c * (a^n - 1)/(a - 1)) \mod m
* above, but we can't compute this without arbitrary precision
* arithmetic. Fortunately, there is an O(log(i)) jump ahead algorithm
* from Forrest B. Brown <9>, which we've implemented here. */
while (by > 0) {
if (by & 1u) {
actmult *= curmult;
actplus = actplus * curmult curplus;
}
curplus = (curmult 1u) * curplus;
curmult *= curmult;
by >>= 1;
}
rng->state = actmult * rng->state actplus;
}
#endif /* RANDOM_H_IMPLEMENTATION */
#define PRNG64_PCG_AVAILABLE (__SIZEOF_INT128__)
#if PRNG64_PCG_AVAILABLE
# define PRNG64_PCG_MULT \
(((__uint128_t)2549297995355413924u << 64) | \
4865540595714422341u)
typedef struct { __uint128_t state, stream; } PRNG64Pcg;
static inline void
prng64_pcg_init(PRNG64Pcg *rng,
uint64_t const seed[2],
uint64_t const stream[2])
{
rng->state = ((__uint128_t)seed[0] << 64) | seed[1];
rng->stream = ((__uint128_t)stream[0] << 64) | 1u | stream[1];
}
#if !TRNG_NOT_AVAILABLE
static inline void
prng64_pcg_randomize(void *rng)
{
PRNG64Pcg *r = (PRNG64Pcg*)rng;
trng_write(&r->state, sizeof r->state);
trng_write(&r->stream, sizeof r->stream);
r->stream |= 1;
}
#endif
static inline uint64_t
prng64_pcg(void *rng)
{
/* Period: 2^{128} with 2^{127} streams
* BigCrush: Passes
* PractRand: Passes (>32T) */
PRNG64Pcg *r = (PRNG64Pcg*)rng;
uint64_t const xorshifted =
((uint64_t)(r->state >> 64)) ^ (uint64_t)r->state;
uint64_t const rot = r->state >> 122;
r->state = r->state * PRNG64_PCG_MULT r->stream;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 63u));
}
extern void prng64_pcg_jump(PRNG64Pcg *rng, uint64_t const by[2]);
# ifdef RANDOM_H_IMPLEMENTATION
void
prng64_pcg_jump(PRNG64Pcg *rng, uint64_t const by[2])
{
__uint128_t curmult = PRNG64_PCG_MULT, curplus = rng->stream;
__uint128_t actmult = 1, actplus = 0;
__uint128_t by128 = ((__uint128_t)by[0]) << 64 | by[1];
while (by128 > 0) {
if (by128 & 1u) {
actmult *= curmult;
actplus = actplus * curmult curplus;
}
curplus = (curmult 1u) * curplus;
curmult *= curmult;
by128 >>= 1;
}
rng->state = actmult * rng->state actplus;
}
# endif /* RANDOM_H_IMPLEMENTATION */
#endif /* PRNG64_PCG_AVAILABLE */
/*
* 3.2 Romu PRNGs --------------------------------------------------------------
*
* Rotate-multiply (Romu) PRNGs <7> combine the linear operation of
* multiplication with the nonlinear rotations.
*
* The rotation constants were devised empirically by testing scaled-down
* generators with less state against PractRand. The best of these constants
* were then scale up for use in the full-size generators.
* The multipliers are handcrafted, making sure that they have an irregular
* bit-pattern. A similar technique is employed by B. Widynski's Middle Square
* Weyl Sequence PRNG to obtain several independent streams. <10>
* The duo, trio and quad variants each use 2, 3 and 4 state variables, on
* which the operations above and extra additions and subtractions, are
* applied. The nature of these operations dictates that the state can't have
* every bit set to zero, which mustn't be forgotten when initializing a
* generator.
*
* One can estimate the capacity of the full-sized generators, by running a
* scaled-down version through statistical testing until it fails. This
* theoretically means that the generators won't fail until they have
* generated more than their capacity specifies using a particular seed.
*
* The incredible speed of the Romu generators is due to it being optimized
* with instruction-level parallelism (ILP) in mind. ILP is used in most modern
* processors and allows the execution of multiple instructions in each clock
* cycle whenever possible. Most x86 CPUs can execute up to four instructions
* in each clock cycle. Always leaving one instruction slot per cycle free to
* be used by the surrounding application code, allows the inlined Romu
* generators to introduce almost no delay for the application.
*
* As mentioned above Romu PRNGs are nonlinear, which means that they don't
* have a single cycle that goes through the while period, but rather multiple
* ones with various periods. One must be exceedingly cautious with nonlinear
* generators, because of the likely hood to encounter short cycles. The
* probabilities of such are fortunately known and very low. The upper bound
* probability of periods shorter than 2^k is calculated, given a state
* size of 2^s-1, with 2^{k-s 7}.
*
* We can't follow our already established formula to calculate the probability
* of overlapping sequences. Fortunately, this was also addressed in the Romu
* paper. For n sequences of length 2^L given s bits of state in the generator,
* we can approximate the probability with the formula
* p <= 2^{6.5 l-s}(s-l 1)(n-1)n.
*
* Recommendations:
* - duo_jr for all-out speed
* - quad as the default
*/
#define PRNG_ROMU_ROTL(x,k) (((x) << (k)) | ((x) >> (8 * sizeof(x) - (k))))
typedef struct { uint32_t s[3]; } PRNG32RomuTrio; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG32RomuTrio, prng32_romu_trio)
static inline uint32_t
prng32_romu_trio(void *rng)
{
/* Capacity: >2^{53}
* BigCrush: Passes
* PractRand: Passes (>256T) */
PRNG32RomuTrio *r = (PRNG32RomuTrio*)rng;
uint32_t const s0 = r->s[0], s1 = r->s[1], s2 = r->s[2];
r->s[0] = 3323815723u * s2;
r->s[1] = s1 - s0;
r->s[2] = s2 - s1;
r->s[1] = PRNG_ROMU_ROTL(r->s[1], 6);
r->s[2] = PRNG_ROMU_ROTL(r->s[2], 22);
return s0;
}
typedef struct { uint32_t s[4]; } PRNG32RomuQuad; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG32RomuQuad, prng32_romu_quad)
static inline uint32_t
prng32_romu_quad(void *rng)
{
/* Capacity: >2^{62}
* BigCrush: Passes
* PractRand: Passes (>256T) */
PRNG32RomuQuad *r = (PRNG32RomuQuad*)rng;
uint32_t const s0 = r->s[0], s1 = r->s[1], s2 = r->s[2], s3 = r->s[3];
r->s[0] = 3323815723u * s3;
r->s[1] = s3 PRNG_ROMU_ROTL(s0, 26);
r->s[2] = s2 - s1;
r->s[3] = s2 s0;
r->s[3] = PRNG_ROMU_ROTL(r->s[3], 9);
return s1;
}
typedef struct { uint64_t s[2]; } PRNG64RomuDuo; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG64RomuDuo, prng64_romu_duo)
static inline uint64_t
prng64_romu_duo_jr(void *rng)
{
/* Capacity: >2^{51}
* BigCrush: Passes
* PractRand: Passes (>256T) */
PRNG64RomuDuo *r = (PRNG64RomuDuo*)rng;
uint64_t const s0 = r->s[0];
r->s[0] = 15241094284759029579u * r->s[1];
r->s[1] = r->s[1] - s0;
r->s[1] = PRNG_ROMU_ROTL(r->s[1], 27);
return s0;
}
static inline uint64_t
prng64_romu_duo(void *rng)
{
/* Capacity: >2^{61}
* BigCrush: Passes
* PractRand: Passes (>256T) */
PRNG64RomuDuo *r = (PRNG64RomuDuo*)rng;
uint64_t const s0 = r->s[0];
r->s[0] = 15241094284759029579u * r->s[1];
r->s[1] = PRNG_ROMU_ROTL(r->s[1], 36)
PRNG_ROMU_ROTL(r->s[1], 15) - s0;
return s0;
}
typedef struct { uint64_t s[3]; } PRNG64RomuTrio; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG64RomuTrio, prng64_romu_trio)
static inline uint64_t
prng64_romu_trio(void *rng)
{
/* Capacity: >2^{75}
* BigCrush: Passes
* PractRand: Passes (>256T) */
PRNG64RomuTrio *r = (PRNG64RomuTrio*)rng;
uint64_t const s0 = r->s[0], s1 = r->s[1], s2 = r->s[2];
r->s[0] = 15241094284759029579u * s2;
r->s[1] = s1 - s0;
r->s[2] = s2 - s1;
r->s[1] = PRNG_ROMU_ROTL(r->s[1], 12);
r->s[2] = PRNG_ROMU_ROTL(r->s[2], 44);
return s0;
}
typedef struct { uint64_t s[4]; } PRNG64RomuQuad; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG64RomuQuad, prng64_romu_quad)
static inline uint64_t
prng64_romu_quad(void *rng)
{
/* Capacity: >2^{90}
* BigCrush: Passes
* PractRand: Passes (>256T) */
PRNG64RomuQuad *r = (PRNG64RomuQuad*)rng;
uint64_t const s0 = r->s[0], s1 = r->s[1], s2 = r->s[2], s3 = r->s[3];
r->s[0] = 15241094284759029579u * s3;
r->s[1] = s3 PRNG_ROMU_ROTL(s0, 52);
r->s[2] = s2 - s1;
r->s[3] = s2 s0;
r->s[3] = PRNG_ROMU_ROTL(r->s[3], 19);
return s1;
}
#undef PRNG_ROMU_ROTL
/*
* 3.3 Xorshift PRNGs ----------------------------------------------------------
*
* The Xorshift family of PRNGs combine XOR operations's with bit-shifts and are
* a subset of linear-feedback shift registers (LFSRs). While these generators
* possess better statistical properties than vanilla LCGs they nevertheless
* fail many statistical tests.
*
* Linearity tests specifically are impossible to be passd by vanilla LFSRs,
* hence, similar to the PCGs generators the output must be scrambled. This is
* frequently achieved by using various additions or multiplications.
*
* The xoshiro/xoroshiro generators <8> featured here additionally incorporate
* bit rotations, which improve the state diffusion, as no bit of the operand is
* discarded. We'll be implementing two different scramblers, a faster one with
* a weaker scramble (s/p i.e. '*'/' ') and a slower one with a stronger
* scramble (ss/pp i.e. '**'/' '). It's recommended to use the s/p variants for
* generating floating-point numbers.
*/
#define PRNG_XORSHIFT_ROTL(x,k) (((x) << (k)) | ((x) >> (8 * sizeof(x) - (k))))
typedef struct { uint32_t s[2]; } PRNG32Xoroshiro64; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG32Xoroshiro64, prng32_xoroshiro64)
static inline void
prng32_xoroshiro64_advance(PRNG32Xoroshiro64 *rng) /* 26-9-13 */
{
rng->s[1] ^= rng->s[0];
rng->s[0] = PRNG_XORSHIFT_ROTL(rng->s[0], 26) ^
rng->s[1] ^ (rng->s[1] << 9);
rng->s[1] = PRNG_XORSHIFT_ROTL(rng->s[1], 13);
}
static inline uint32_t
prng32_xoroshiro64s(void *rng)
{
/* Period: 2^{64}-1
* BigCrush: TODO
* PractRand: lower bits fail linear tests, passes all others (>128G) */
PRNG32Xoroshiro64 *r = (PRNG32Xoroshiro64*)rng;
uint32_t const res = r->s[0] * 0x9E3779BB;
prng32_xoroshiro64_advance(r);
return res;
}
static inline uint32_t
prng32_xoroshiro64ss(void *rng)
{
/* Period: 2^{64}-1
* BigCrush: TODO
* PractRand: Passes (>128G) */
PRNG32Xoroshiro64 *r = (PRNG32Xoroshiro64*)rng;
uint32_t const tmp = r->s[0] * 0x9E3779BB;
uint32_t const res = PRNG_XORSHIFT_ROTL(tmp, 5) * 5;
prng32_xoroshiro64_advance(r);
return res;
}
typedef struct { uint32_t s[4]; } PRNG32Xoshiro128; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG32Xoshiro128, prng32_xoshiro128)
static inline void
prng32_xoshiro128_advance(PRNG32Xoshiro128 *rng) /* 0-9-11 */
{
uint32_t const t = rng->s[1] << 9;
rng->s[2] ^= rng->s[0];
rng->s[3] ^= rng->s[1];
rng->s[1] ^= rng->s[2];
rng->s[0] ^= rng->s[3];
rng->s[2] ^= t;
rng->s[3] = PRNG_XORSHIFT_ROTL(rng->s[3], 11);
}
static inline uint32_t
prng32_xoshiro128s(void *rng)
{
/* Period: 2^{128}-1
* BigCrush: TODO
* PractRand: lower bits fail linear tests, passes all others (>128G) */
PRNG32Xoshiro128 *r = (PRNG32Xoshiro128*)rng;
uint32_t const res = r->s[0] r->s[3];
prng32_xoshiro128_advance(r);
return res;
}
static inline uint32_t
prng32_xoshiro128ss(void *rng)
{
/* Period: 2^{128}-1
* BigCrush: TODO
* PractRand: Passes (>128G) */
PRNG32Xoshiro128 *r = (PRNG32Xoshiro128*)rng;
uint32_t const tmp = r->s[1] * 5;
uint32_t const res = PRNG_XORSHIFT_ROTL(tmp, 7) * 9;
prng32_xoshiro128_advance(r);
return res;
}
typedef struct { uint64_t s[2]; } PRNG64Xoroshiro128; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG64Xoroshiro128, prng64_xoroshiro128)
static inline void
prng64_xoroshiro128_advance(PRNG64Xoroshiro128 *rng) /* 24-16-37 */
{
rng->s[1] ^= rng->s[0];
rng->s[0] = PRNG_XORSHIFT_ROTL(rng->s[0], 24) ^
rng->s[1] ^ (rng->s[1] << 16);
rng->s[1] = PRNG_XORSHIFT_ROTL(rng->s[1], 37);
}
static inline uint64_t
prng64_xoroshiro128p(void *rng)
{
/* Period: 2^{128}-1
* BigCrush: Passes
* PractRand: lower bits fail linear tests, passes all others (>128G) */
PRNG64Xoroshiro128 *r = (PRNG64Xoroshiro128*)rng;
uint64_t const res = r->s[0] r->s[1];
prng64_xoroshiro128_advance(r);
return res;
}
static inline uint64_t
prng64_xoroshiro128ss(void *rng)
{
/* Period: 2^{128}-1
* BigCrush: Passes
* PractRand: Passes (>512G) */
PRNG64Xoroshiro128 *r = (PRNG64Xoroshiro128*)rng;
uint64_t const tmp = r->s[0] * 5;
uint64_t const res = PRNG_XORSHIFT_ROTL(tmp, 7) * 9;
prng64_xoroshiro128_advance(r);
return res;
}
typedef struct { uint64_t s[4]; } PRNG64Xoshiro256; /* not all zero */
CAULDRON_MAKE_PRNG_NOTALLZERO_RANDOMIZE(PRNG64Xoshiro256, prng64_xoshiro256)
static inline void
prng64_xoshiro256_advance(PRNG64Xoshiro256 *rng) /* 0-17-54 */
{
uint64_t const t = rng->s[1] << 17;
rng->s[2] ^= rng->s[0];
rng->s[3] ^= rng->s[1];
rng->s[1] ^= rng->s[2];
rng->s[0] ^= rng->s[3];
rng->s[2] ^= t;
rng->s[3] = PRNG_XORSHIFT_ROTL(rng->s[3], 45);
}
static inline uint64_t
prng64_xoshiro256p(void *rng)
{
/* Period: 2^{256}-1
* BigCrush: Passes
* PractRand: lower bits fail linear tests, passes all others (>128G) */
PRNG64Xoshiro256 *r = (PRNG64Xoshiro256*)rng;
uint64_t const res = r->s[0] r->s[3];
prng64_xoshiro256_advance(r);
return res;
}
static inline uint64_t
prng64_xoshiro256ss(void *rng)
{
/* Period: 2^{256}-1
* BigCrush: Passes
* PractRand: Passes (>512G) */
PRNG64Xoshiro256 *r = (PRNG64Xoshiro256*)rng;
uint64_t const tmp = r->s[1] * 5;
uint64_t const res = PRNG_XORSHIFT_ROTL(tmp, 7) * 9;
prng64_xoshiro256_advance(r);
return res;
}
/* There are also 512/1024-bit xoroshiro variant's, although 256-bits are
* already more than enough. */
#undef PRNG_XORSHIFT_ROTL
/*
* Every LFSR has specific jump polynomials that can be used to efficiently
* jump ahead, we supply some precomputed ones bellow.
*
* For more interested readers here is how to obtain Vigna's script to generate
* these polynomials. You should be able to generate full jump tables for all of
* the generators, though I only got xoroshiro128 to work properly:
*
* Generate the full xoroshiro128 jump table:
* 1. Download and extract "https://web.archive.org/web/20180909014435/
* http://xoroshiro.di.unimi.it/xorshift-1.2.tgz"
* 2. Install python2 and Fermat (http://home.bway.net/lewis)
* 3. Replace "fermat" in xorshift-1.2 with the name of the Fermat
* executable (in my case "fer64"):
* $ sed -i "s/fermat/fer64/g" `find xorshift-1.2 -type f`
* 4. Replace "#!/usr/bin/python" in jump.py with "#!/usr/bin/python2".
* 5. $ cd xorshift-1.2/full/128roshiro64/
* $ j=0
* $ while [[ $j -le 128 ]] ; do
* $ echo -e -n $j " " | head -c4;
* $ grep 24-16-37 prim.txt | ../common/jump.sh $j
* $ j=$((j 1))
* $ done
*/