forked from erlang/otp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrand.erl
More file actions
3778 lines (3334 loc) · 139 KB
/
Copy pathrand.erl
File metadata and controls
3778 lines (3334 loc) · 139 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
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
594
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
%%
%% %CopyrightBegin%
%%
%% SPDX-License-Identifier: Apache-2.0
%%
%% Copyright Ericsson AB 2015-2026. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%% =====================================================================
%% Multiple PRNG module for Erlang/OTP
%% Copyright (c) 2015-2016 Kenji Rikitake
%%
%% exrop (xoroshiro116+) added, statistical distribution
%% improvements and uniform_real added by the Erlang/OTP team 2017
%% =====================================================================
-module(rand).
-moduledoc """
Pseudo random number generation
This module provides Pseudo Random Number Generation and implements
a number of [base generator algorithms](#algorithms). Most are provided
through a [plug-in framework](#plug-in-framework)
that adds essential features to the base generators.
PRNGs in general, and so the algorithms in this module, are mostly used
for test and simulation. They are designed for good statistical
quality and high generation speed.
A generator algorithm, for each iteration, takes a state as input
and produces a raw pseudo random number and a new state to be used
for the next iteration.
A particular state always produces the same raw number and new state.
The initial state is produced from a [seed](`seed/1`).
This makes it possible to reproduce for example a simulation with the same
pseudo random number sequence, by using the same seed.
There are also the functions `export_seed/0` and `export_seed_s/1`
that capture the PRNG state in an `t:export_state/0`,
that can be used to start from a known state.
This property, and others, make the algorithms in this module
unsuitable for cryptographical applications, but in the `m:crypto` module
there are such generators, for this module's
[plug-in framework](#plug-in-framework).
See `crypto:rand_seed_s/0` and `crypto:rand_seed_alg_s/1`.
At the end of this module documentation there are some
[niche algorithms](#niche-algorithms) that do not use
this module's normal [plug-in framework](#plug-in-framework).
They are useful for special purposes like fast generation
when quality is not essential, for seeding other generators, and such.
[](){: #plug-in-framework } Plug-in framework
---------------------------------------------
The raw pseudo random numbers produced by the base generators
are only appropriate in some cases such as power of two ranges
less than the generator size, and some have quirks,
for example weak low bits. Therefore, the Plug-in Framework
implements a common [API](#plug-in-framework-api) for all base generators,
that add essential or useful funcionality:
* Keeping the generator [state](`seed/1`) in the process dictionary.
* Automatic [seeding](`seed/1`).
* Seeding support for [manual seeding](`seed/2`) to avoid common pitfalls.
* Generating [integers](`t:integer/0`) with
[uniform distribution](`uniform/1`), on *any* range, without bias.
* Generating [floating-point numbers](`t:float/0`) with
[uniform distribution](`uniform/0`).
* Generating [floating-point numbers](`t:float/0`) with
[normal distribution](`normal/0`), standard normal distribution
or [specified mean and variance](`normal/2`).
* Generating any number of [bytes](`bytes/1`).
* [Jumping](`jump/1`) the generator ahead (multiple non-overlapping
sequences), in algorithms that support that.
[](){: #usage }
### Usage and examples
Decide if the PRNG state should be stored in the process dictionary
of the calling process (implicit state), or in a state variable
for the calling code to keep track of (explicit state).
Initialize (seed) a generator, which selects the PRNG
algorithm and creates the initial state. Either use an explicit
`Seed` value which makes it possible to reproduce the PRNG sequence,
or use an automatic seed. If you use the implicit state and omit this step,
you will get the [_default algorithm_](#default-algorithm)
with an automatic seed.
Then the generator functions that, for example; generate range limited
uniformly distributed integers, shuffle a list, and so on, can be called.
#### Seeding the generator
Seeding (initializing) is done by calling one of the `seed/1` or
`seed_s/1` functions, which also selects which [algorithm](#algorithms)
to use. The `seed/1` functions store the generator and initial state
in the process dictionary, while the `seed_s/1` functions
only return the initial state.
The seed functions that do not have a `Seed` argument
create an automatic seed which is designed to be unique to the created
generator instance; see `seed_s/1`.
If an automatic seed is not desired, the seed functions that have a
[`Seed`](`t:seed/0`) argument should be used. The argument has
3 possible formats; see the `t:seed/0` type description.
There are also seeding functions for generators in the `m:crypto` module.
See the section [Plug-In Generators](`m:crypto#plug-in-generators`).
#### Using the generator
The [Plug-in framework API](#plug-in-framework-api) generator functions
named with the suffix `_s`, with a few exceptions, take an explicit state
as their last argument and return the new state as the last element
in the returned tuple. The new state shall be used when calling
the next generator function, and so on. The process dictionary is not used.
Sibling functions without that suffix operate on the implicit state
stored in the process dictionary, and only return their "interesting"
output value. If the process dictionary has no stored implicit state,
[`seed(default)`](`seed/1`) is called to create an automatic seed
for the [_default algorithm_](#default-algorithm), as initial state.
*Generator functions*:
* `uniform/1` and `uniform_s/2` generate *uniformly distributed integers*
on **any** (unlimited) specified range, without bias.
* `uniform/0`, `uniform_s/1`, `uniform_real/0` and `uniform_real_s/1`
generate *uniformly distributed floating point numbers*
on the range [0.0, 1.0).
* `bytes/1` and `bytes_s/2` generate *uniformly distributed bytes*.
See the note under `bytes_s/2` about efficiency.
* `shuffle/1` and `shuffle_s/2` *shuffle a list*.
Those generator functions use one or more raw numbers from the generator
to do perform their tasks, which actually may be a bit tricky
to do correctly and efficiently.
[](){: #normal-distribution-caveat } *Generator functions*:
* `normal/0` and `normal_s/1` generate *standard normal distribution*
floating point numbers.
* `normal/2` and `normal_s/3` generate *normal distribution*
floating poing numbers with specified *mean value and variance*.
Those generator functions have to use a number of floating point
calculations, that on different platforms with different math library
implementations, optimizations, compilation flags such as
gcc's `-ffast-math`, etc, may produce slightly different values.
Furthermore these slightly different values may cause the implementation
to do a recursive retry on one platform that is not done on another,
so the produced sequences may derail and get out of sync.
In other words, using these generator functions may cause the generated
number sequence to be different on a different platform or on a different
Erlang/OTP systems. Despite using the same seed.
In the Shell Examples section just below, it is mentioned how to
generate a textbook Box-Müller method standard distribution number,
which is much slower than the Ziggurat Method used by the `normal`*
functions:
```erlang
math:sqrt(-2 * math:log(rand:uniform_real()))
* math:cos(math:pi() * rand:uniform())
```
That method always uses 2 raw generator numbers, so it will not derail,
but may still produce slightly different numbers on different platforms.
#### _Shell Examples_
```erlang
%% Generate two uniformly distibuted floating point numbers.
%%
%% By not calling a [seed](`seed/1`) function, this uses
%% the generator state and algorithm in the process dictionary.
%% If there is no state there, [`seed(default)`](`seed/1`)
%% is implicitly called first:
%%
1> R0 = rand:uniform(),
is_float(R0) andalso 0.0 =< R0 andalso R0 < 1.0.
true
2> R1 = rand:uniform(),
is_float(R1) andalso 0.0 =< R1 andalso R1 < 1.0.
true
%% Generate a uniformly distributed integer in the range 1 .. 4711:
%%
3> K0 = rand:uniform(4711),
is_integer(K0) andalso 1 =< K0 andalso K0 =< 4711.
true
%% Generate a binary with 16 bytes, uniformly distributed:
%%
4> B0 = rand:bytes(16),
byte_size(B0) == 16.
true
%% Select and initialize a specified algorithm,
%% with an automatic default seed, then generate
%% a floating point number:
%%
5> rand:seed(exro928ss).
6> R2 = rand:uniform(),
is_float(R2) andalso 0.0 =< R2 andalso R2 < 1.0.
true
%% Select and initialize a specified algorithm
%% with a specified seed, then generate
%% a floating point number:
%%
7> rand:seed(exro928ss, 123456789).
8> R3 = rand:uniform().
0.48303622772415256
%% Select and initialize a specific algorithm,
%% with an automatic default seed, using the functional API
%% with explicit generator state, then generate
%% two floating point numbers.
%%
9> S0 = rand:seed_s(exsss).
10> {R4, S1} = rand:uniform_s(S0),
is_float(R4) andalso 0.0 =< R4 andalso R4 < 1.0.
true
11> {R5, S2} = rand:uniform_s(S1),
is_float(R5) andalso 0.0 =< R5 andalso R5 < 1.0.
true
%% Repeat the first after seed
12> {R4, _} = rand:uniform_s(S0).
%% Generate a standard normal distribution number
%% using the built-in fast Ziggurat Method:
%%
13> {SND0, S3} = rand:normal_s(S2),
is_float(SND0).
true
%% Generate a normal distribution number
%% with mean -3 and variance 0.5:
%%
14> {ND0, S4} = rand:normal_s(-3, 0.5, S3),
is_float(ND0).
true
%% Generate a textbook basic form Box-Müller
%% standard normal distribution number, which has the same
%% distribution as the built-in Ziggurat Method above,
%% but is much slower:
%%
15> R6 = rand:uniform_real(),
is_float(R6) andalso 0.0 < R6 andalso R6 < 1.0.
true
16> R7 = rand:uniform(),
is_float(R7) andalso 0.0 =< R7 andalso R7 < 1.0.
true
%% R6 cannot be equal to 0.0 so math:log/1 will never fail
17> SND1 = math:sqrt(-2 * math:log(R6)) * math:cos(math:pi() * R7).
%% Shuffle a deck of cards from a fixed seed,
%% with a cryptographically unpredictable algorithm:
18> Deck0 = [{Rank,Suit} ||
Rank <- lists:seq(2, 14),
Suit <- [clubs,diamonds,hearts,spades]].
19> S5 = crypto:rand_seed_alg(crypto_aes, "Nothing up my sleeve").
20> {Deck, S6} = rand:shuffle_s(Deck0, S5).
21> Deck.
[{2,spades}, {12,spades}, {14,diamonds}, {11,clubs},
{6,spades}, {2,hearts}, {13,diamonds}, {12,hearts},
{10,clubs}, {7,diamonds}, {2,diamonds}, {9,diamonds},
{4,hearts}, {9,hearts}, {6,clubs}, {3,spades},
{3,diamonds}, {14,clubs}, {9,spades}, {10,hearts},
{3,hearts}, {4,spades}, {13,hearts}, {5,hearts},
{7,hearts}, {7,clubs}, {8,spades}, {14,spades},
{11,spades}, {12,clubs}, {5,diamonds}, {12,diamonds},
{4,diamonds}, {9,clubs}, {14,hearts}, {2,clubs},
{10,diamonds}, {13,spades}, {6,hearts}, {4,clubs},
{7,spades}, {5,spades}, {10,spades}, {5,clubs},
{8,diamonds}, {6,diamonds}, {8,clubs}, {11,hearts},
{13,clubs}, {11,diamonds}, {3,clubs}, {8,hearts}]
```
[](){: #algorithms } Algorithms
-------------------------------
The base generator algorithms implement the
[Xoroshiro and Xorshift algorithms](http://xorshift.di.unimi.it)
by Sebastiano Vigna. During an iteration they generate an integer
(at least 58-bit) and operate on a state of several integers.
The size of these integers is chosen to not require bignum arithmetic
on 64-bit platforms, which facilitates fast integer operations,
in particular when handled by the JIT VM.
For most algorithms, jump functions are provided for generating
non-overlapping sequences. A jump function perform a calculation
equivalent to a large number of repeated state iterations,
but execute in a time roughly equivalent to one regular iteration
per generator bit.
By using a jump function instead of starting several generators
from different seeds it is assured that the generated sequences
do not overlap. The alternative of using different seeds
may accidentally start the generators in sequence positions
that are close to each other, but a jump function jumps
to a sequence position so far ahead that the generator
at the jumped from position will never arrive
at the jumped to position.
To create numbers with normal distribution the
[Ziggurat Method by Marsaglia and Tsang](http://www.jstatsoft.org/v05/i08)
is used on the output from a base generator.
The following algorithms are provided:
- **`exsss`**, the [_default algorithm_](#default-algorithm)
*(Since OTP 22.0)*
Xorshift116\*\*, 58 bits precision and period of 2^116-1.
Jump function: equivalent to 2^64 calls.
This is the Xorshift116 generator combined with the StarStar scrambler from
the 2018 paper by David Blackman and Sebastiano Vigna:
[Scrambled Linear Pseudorandom Number Generators](http://vigna.di.unimi.it/ftp/papers/ScrambledLinear.pdf)
The generator does not use 58-bit rotates so it is faster than the
Xoroshiro116 generator, and when combined with the StarStar scrambler
it does not have any weak low bits like `exrop` (Xoroshiro116+).
Alas, this combination is about 10% slower than `exrop`, but despite that
it is the [_default algorithm_](#default-algorithm) thanks to
its statistical qualities.
- **`exro928ss`** *(Since OTP 22.0)*
Xoroshiro928\*\*, 58 bits precision and a period of 2^928-1.
Jump function: equivalent to 2^512 calls.
This is a 58 bit version of Xoroshiro1024\*\*, from the 2018 paper by
David Blackman and Sebastiano Vigna:
[Scrambled Linear Pseudorandom Number Generators](http://vigna.di.unimi.it/ftp/papers/ScrambledLinear.pdf)
that on a 64 bit Erlang system executes only about 40% slower than the
[*default `exsss` algorithm*](#default-algorithm)
but with much longer period and better statistical properties,
but on the flip side a larger state.
Many thanks to Sebastiano Vigna for his help with the 58 bit adaption.
- **`exrop`** *(Since OTP 20.0)*
Xoroshiro116+, 58 bits precision and period of 2^116-1.
Jump function: equivalent to 2^64 calls.
- **`exs1024s`** *(Since OTP 20.0)*
Xorshift1024\*, 64 bits precision and a period of 2^1024-1
Jump function: equivalent to 2^512 calls.
Since this generator operates on 64-bit integers that are bignums
on 64 bit platforms, it is much slower than `exro928ss` above.
- **`exsp`** *(Since OTP 20.0)*
Xorshift116+, 58 bits precision and period of 2^116-1
Jump function: equivalent to 2^64 calls.
This is a corrected version of a previous
[_default algorithm_](#default-algorithm) (`exsplus`, _deprecated_),
that was superseded by Xoroshiro116+ (`exrop`). Since this algorithm
does not use rotate operations it executes a little (say < 15%) faster
than `exrop` (that has to do a 58 bit rotate,
for which there is no native instruction).
See the [algorithms' homepage](http://xorshift.di.unimi.it).
[](){: #default-algorithm }
### Default Algorithm
The current _default algorithm_ is
[`exsss` (Xorshift116\*\*)](#algorithms). If a specific algorithm is
required, ensure to always use `seed/1` to initialize the state.
In many API functions in this module, the atom `default` can be used
instead of an algorithm name, and is currently an alias for `exsss`.
In a future Erlang/OTP release this might be a different algorithm.
The _default algorithm_ is selected to be one with high speed,
small state and "good enough" statistical properties.
If it is essential to reproduce the same PRNG sequence
on a later Erlang/OTP release, use `seed/2` or `seed_s/2`
to select *both* a specific algorithm and the seed value.
### Old Algorithms
Undocumented (old) algorithms are deprecated but still implemented so old code
relying on them will produce the same pseudo random sequences as before.
> #### Note {: .info }
>
> There were a number of problems in the implementation of
> the now undocumented algorithms, which is why they are deprecated.
> The new algorithms are a bit slower but do not have these problems:
>
> Uniform integer ranges had a skew in the probability distribution
> that was not noticeable for small ranges but for large ranges
> less than the generator's precision the probability to produce
> a low number could be twice the probability for a high.
>
> Uniform integer ranges larger than or equal to the generator's precision
> used a floating point fallback that only calculated with 52 bits
> which is smaller than the requested range and therefore all numbers
> in the requested range were not even possible to produce.
>
> Uniform floats had a non-uniform density so small values for example
> less than 0.5 had got smaller intervals decreasing as the generated value
> approached 0.0 although still uniformly distributed for sufficiently large
> subranges. The new algorithms produces uniformly distributed floats
> of the form `N * 2.0^(-53)` hence they are equally spaced.
### Quality of the Generated Numbers
> #### Note {: .info }
>
> The builtin random number generator algorithms are not cryptographically
> strong. If a *cryptographically strong* random number generator is needed,
> use for example `crypto:rand_seed_s/0` or `crypto:rand_seed_alg_s/1`.
>
> There are also generators for *cryptographically unpredictable*
> pseudo random numbers: see `crypto:rand_seed_alg/2` and
> `crypto:rand_seed_alg_s/2`. They are generated using cryptographical
> primitives so the statistical quality is impeccable, but the
> generated sequence can be repeated, and therefore cannot be regarded as
> *cryptographically strong*.
>
> The generators in the [`crypto`](`m:crypto#plug-in-generators`)
> module are much slower at generating numbers and/or require
> a much larger state than the generators in this module.
For all these generators except `exro928ss` and `exsss` the lowest bit(s)
have got a slightly less random behaviour than all other bits.
1 bit for `exrop` (and `exsp`), and 3 bits for `exs1024s`. See for example
this explanation in the
[Xoroshiro128+](http://xoroshiro.di.unimi.it/xoroshiro128plus.c)
generator source code:
> Beside passing BigCrush, this generator passes the PractRand test suite
> up to (and included) 16TB, with the exception of binary rank tests,
> which fail due to the lowest bit being an LFSR; all other bits pass all
> tests. We suggest to use a sign test to extract a random Boolean value.
If this is a problem; to generate a boolean with these algorithms,
use something like this:
```erlang
(rand:uniform(256) > 128) % -> boolean()
```
```erlang
((rand:uniform(256) - 1) bsr 7) % -> 0 | 1
```
For a general range, with `N = 1` for `exrop`, and `N = 3` for `exs1024s`:
```erlang
(((rand:uniform(Range bsl N) - 1) bsr N) + 1)
```
The floating point generating functions in this module waste the lowest bits
when converting from an integer so they avoid this snag.
[](){: #niche-algorithms } Niche algorithms
-------------------------------------------
The [niche algorithms API](#niche-algorithms-api) contains
special purpose algorithms that do not use the
[plug-in framework](#plug-in-framework), mainly for performance reasons.
Since these algorithms lack the plug-in framework support, generating numbers
on a range other than the base generator's range may become a problem.
There are at least four ways to do this, assuming the `Range` is less than
the generator's range:
[](){: #modulo-method }
- **Modulo**
To generate a number `V` on the range `0 .. Range-1`:
> Generate a number `X`.
> Use `V = X rem Range` as your value.
This method uses `rem`, that is, the remainder of an integer division,
which is a slow operation.
Low bits from the generator propagate straight through to
the generated value, so if the generator has got weaknesses
in the low bits this method propagates them too.
If `Range` is not a divisor of the generator range, the generated numbers
have a bias. Example:
Say the generator generates a byte, that is, the generator range
is `0 .. 255`, and the desired range is `0 .. 99` (`Range = 100`).
Then there are 3 generator outputs that produce the value `0`,
these are `0`, `100` and `200`.
But there are only 2 generator outputs that produce the value `99`,
which are `99` and `199`. So the probability for a value `V` in `0 .. 55`
is 3/2 times the probability for the other values `56 .. 99`.
If `Range` is much smaller than the generator range, then this bias
gets hard to detect. The rule of thumb is that if `Range` is smaller
than the square root of the generator range, the bias is small enough.
Example:
A byte generator when `Range = 20`. There are 12 (`256 div 20`)
possibilities to generate the highest numbers and one more to generate
a number `V < 16` (`256 rem 20`). So the probability is 13/12
for a low number versus a high. To detect that difference with
some confidence you would need to generate a lot more numbers
than the generator range, `256` in this small example.
[](){: #truncated-multiplication-method }
- **Truncated multiplication**
To generate a number `V` in the range `0 .. Range-1`, when you have
a generator with a power of 2 range (`0 .. 2^Bits-1`):
> Generate a number `X`.
> Use `V = X * Range bsr Bits` as your value.
If the multiplication `X * Range` creates a bignum
this method becomes very slow.
High bits from the generator propagate through to the generated value,
so if the generator has got weaknesses in the high bits this method
propagates them too.
If `Range` is not a divisor of the generator range, the generated numbers
have a bias, pretty much as for the [Modulo](#modulo-method) method above.
[](){: #shift-or-mask-method }
- **Shift or mask**
To generate a number in a power of 2 range (`0 .. 2^RBits-1`),
when you have a generator with a power of 2 range (`0 .. 2^Bits`):
> Generate a number `X`.
> Use `V = X band ((1 bsl RBits)-1)` or `V = X bsr (Bits-RBits)`
> as your value.
Masking with `band` preserves the low bits, and right shifting
with `bsr` preserves the high, so if the generator has got weaknesses
in high or low bits; choose the right operator.
If the generator has got a range that is not a power of 2
and this method is used anyway, it introduces bias in the same way
as for the [Modulo](#modulo-method) method above.
[](){: #rejection-method }
- **Rejection**
> Generate a number `X`.
> If `X` is in the range, use it as your value,
> otherwise reject it and repeat.
In theory it is not certain that this method will ever complete,
but in practice you ensure that the probability of rejection is low.
Then the probability for yet another iteration decreases exponentially
so the expected mean number of iterations will often be between 1 and 2.
Also, since base generators in general are full length generators,
they traverse all values of their state, so a value that will break the loop
must eventually be generated.
These methods can be combined, such as using
the [Modulo](#modulo-method) method and only if the generator value
would create bias use [Rejection](#rejection-method).
Or using [Shift or mask](#shift-or-mask-method) to reduce the size
of a generator value so that
[Truncated multiplication](#truncated-multiplication-method)
will not create a bignum.
The recommended way to generate a floating point number
(IEEE 745 Double, that has got a 53-bit mantissa) in the range
`0 .. 1`, that is `0.0 =< V < 1.0` is to generate a 53-bit number `X`
and then use `V = X * 2#1.0*e-53` as your value.
This will create a value of the form N*2^-53 with equal probability
for every possible N for the range.
""".
-moduledoc(#{since => "OTP 18.0"}).
-export([seed_s/1, seed_s/2, seed/1, seed/2,
export_seed/0, export_seed_s/1,
uniform/0, uniform/1, uniform_s/1, uniform_s/2,
uniform_real/0, uniform_real_s/1,
bytes/1, bytes_s/2,
jump/0, jump/1,
normal/0, normal/2, normal_s/1, normal_s/3,
shuffle/1, shuffle_s/2
]).
%% Utilities
-export([exsp_next/1, exsp_jump/1, splitmix64_next/1,
mwc59/1, mwc59_value32/1, mwc59_value/1, mwc59_float/1,
mwc59_seed/0, mwc59_seed/1]).
%% Test, dev and internal
-export([exro928_jump_2pow512/1, exro928_jump_2pow20/1,
exro928_seed/1, exro928_next/1, exro928_next_state/1,
format_jumpconst58/1, seed58/2]).
%% Debug
-export([make_float/3, float2str/1, bc64/1]).
-compile({inline, [exs64_next/1, exsp_next/1, exsss_next/1,
exs1024_next/1, exs1024_calc/2,
exro928_next_state/4,
exrop_next/1, exrop_next_s/2,
shuffle_new_bits/1,
mwc59_value/1,
get_52/1, normal_kiwi/1]}).
-define(DEFAULT_ALG_HANDLER, exsss).
-define(SEED_DICT, rand_seed).
%% =====================================================================
%% Bit fiddling macros
%% =====================================================================
-define(BIT(Bits), (1 bsl (Bits))).
-define(MASK(Bits), (?BIT(Bits) - 1)).
-define(MASK(Bits, X), ((X) band ?MASK(Bits))).
-define(
BSL(Bits, X, N),
%% N is evaluated 2 times
(?MASK((Bits)-(N), (X)) bsl (N))).
-define(
ROTL(Bits, X, N),
%% Bits is evaluated 2 times
%% X is evaluated 2 times
%% N i evaluated 3 times
(?BSL((Bits), (X), (N)) bor ((X) bsr ((Bits)-(N))))).
-define(
BC(V, N),
bc((V), ?BIT((N) - 1), N)).
%%-define(TWO_POW_MINUS53, (math:pow(2, -53))).
%%-define(TWO_POW_MINUS53, 1.11022302462515657e-16).
-define(TWO_POW_MINUS53, 2#1.0#e-53).
%% =====================================================================
%% Types
%% =====================================================================
-doc "`0 .. (2^64 - 1)`".
-type uint64() :: 0..?MASK(64).
-doc "`0 .. (2^58 - 1)`".
-type uint58() :: 0..?MASK(58).
%% This depends on the algorithm handler function
-type alg_state() ::
exsplus_state() | exro928_state() | exrop_state() | exs1024_state() |
exs64_state() | dummy_state() | term().
%% This is the algorithm handling definition within this module,
%% and the type to use for plug-ins.
%%
%% The 'type' field must be recognized by the module that implements
%% the algorithm, to interpret an exported state.
%%
%% The 'bits' field indicates how many bits the integer
%% returned from 'next' has got, i.e 'next' shall return
%% an random integer in the range 0 .. (2^Bits - 1).
%% At least 55 bits is required for the floating point
%% producing fallbacks, but 56 bits would be more future proof.
%%
%% The fields 'next', 'uniform' and 'uniform_n'
%% implement the algorithm. If 'uniform' or 'uniform_n'
%% is not present there is a fallback using 'next' and either
%% 'bits' or the deprecated 'max'. The 'next' function
%% must generate a word with at least 56 good random bits.
%%
%% The 'weak_low_bits' field indicate how many bits are of
%% lesser quality and they will not be used by the floating point
%% producing functions, nor by the range producing functions
%% when more bits are needed, to avoid weak bits in the middle
%% of the generated bits. The lowest bits from the range
%% functions still have the generator's quality.
%%
-type alg_handler() :: alg_handler(alg()).
-type alg_handler(Alg) ::
#{type := Alg,
bits => non_neg_integer(),
weak_low_bits => 0..3,
max => non_neg_integer(), % Deprecated
next :=
fun ((alg_state()) -> {non_neg_integer(), alg_state()}),
uniform =>
fun ((state()) -> {float(), state()}),
uniform_n =>
fun ((pos_integer(), state()) -> {pos_integer(), state()}),
jump =>
fun ((state()) -> state()),
bytes =>
fun ((non_neg_integer(), state()) -> {binary(), state()})}.
%% Algorithm state
-doc "Algorithm-dependent state.".
-type state() :: {alg_handler(), alg_state()}.
-type builtin_alg() ::
exsss | exro928ss | exrop | exs1024s | exsp | exs64 | exsplus |
exs1024 | dummy.
-type alg() :: builtin_alg() | atom().
-doc "Algorithm-dependent state that can be printed or saved to file.".
-type export_state() :: {alg(), alg_state()}.
-doc """
Generator seed value.
A single integer is the easiest to use. It is set as the initial state
of a [SplitMix64](`splitmix64_next/1`) generator. The sequential
output values of that generator are then used for setting the actual
generator's internal state, after masking to the proper word size
and avoiding zero values, if necessary.
A list of integers sets the generator's internal state directly, after
algorithm-dependent checks of the value and masking to the proper word size.
The number of integers must be equal to the number of state words
in the generator. This format would only be needed in special cases.
A traditional 3-tuple of integers is passed through algorithm-dependent
hashing functions to create the generator's initial state. This format is
inherited from this module's predecessor, the `m:random` module,
where the 3-tuple from `erlang:now/0` (also now deprectated) was often used
for seeding to get some uniqueness.
""".
-type seed() :: [integer()] | integer() | {integer(), integer(), integer()}.
-export_type(
[builtin_alg/0, alg/0, alg_handler/0, alg_handler/1, alg_state/0,
state/0, export_state/0, seed/0]).
-export_type(
[exsplus_state/0, exro928_state/0, exrop_state/0, exs1024_state/0,
exs64_state/0, mwc59_state/0, dummy_state/0]).
-export_type(
[uint58/0, uint64/0, splitmix64_state/0]).
%% =====================================================================
%% Range macro and helper
%% =====================================================================
-define(
uniform_range(Range, AlgHandler, R, V, MaxMinusRange, I),
if
0 =< (MaxMinusRange) ->
if
%% Really work saving in odd cases;
%% large ranges in particular
(V) < (Range) ->
{(V) + 1, {(AlgHandler), (R)}};
true ->
(I) = (V) rem (Range),
if
(V) - (I) =< (MaxMinusRange) ->
{(I) + 1, {(AlgHandler), (R)}};
true ->
%% V in the truncated top range
%% - try again
?FUNCTION_NAME((Range), {(AlgHandler), (R)})
end
end;
true ->
uniform_range((Range), (AlgHandler), (R), (V))
end).
%% For ranges larger than the algorithm bit size
uniform_range(Range, #{next:=Next, bits:=Bits} = AlgHandler, R, V) ->
WeakLowBits = maps:get(weak_low_bits, AlgHandler, 0),
%% Maybe waste the lowest bit(s) when shifting in new bits
Shift = Bits - WeakLowBits,
ShiftMask = bnot ?MASK(WeakLowBits),
RangeMinus1 = Range - 1,
if
(Range band RangeMinus1) =:= 0 -> % Power of 2
%% Generate at least the number of bits for the range
{V1, R1, _} =
uniform_range(
Range bsr Bits, Next, R, V, ShiftMask, Shift, Bits),
{(V1 band RangeMinus1) + 1, {AlgHandler, R1}};
true ->
%% Generate a value with at least two bits more than the range
%% and try that for a fit, otherwise recurse
%%
%% Just one bit more should ensure that the generated
%% number range is at least twice the size of the requested
%% range, which would make the probability to draw a good
%% number better than 0.5. And repeating that until
%% success i guess would take 2 times statistically amortized.
%% But since the probability for fairly many attemtpts
%% is not that low, use two bits more than the range which
%% should make the probability to draw a bad number under 0.25,
%% which decreases the bad case probability a lot.
{V1, R1, B} =
uniform_range(
Range bsr (Bits - 2), Next, R, V, ShiftMask, Shift, Bits),
I = V1 rem Range,
if
(V1 - I) =< (1 bsl B) - Range ->
{I + 1, {AlgHandler, R1}};
true ->
%% V1 drawn from the truncated top range
%% - try again
{V2, R2} = Next(R1),
uniform_range(Range, AlgHandler, R2, V2)
end
end.
%%
uniform_range(Range, Next, R, V, ShiftMask, Shift, B) ->
if
Range =< 1 ->
{V, R, B};
true ->
{V1, R1} = Next(R),
%% Waste the lowest bit(s) when shifting in new bits
uniform_range(
Range bsr Shift, Next, R1,
((V band ShiftMask) bsl Shift) bor V1,
ShiftMask, Shift, B + Shift)
end.
%% =====================================================================
%% API
%% =====================================================================
%% Return algorithm and seed so that RNG state can be recreated with seed/1
-doc """
Export the seed value.
Returns the random number state in an external format.
To be used with `seed/1`.
#### _Shell Example_
```erlang
%% Initialize a predictable PRNG sequence
1> S = rand:seed(exsss, 4711).
%% Export the (initial) state
2> E = rand:export_seed().
%% Generate an integer N in the interval 1 .. 1_000_000
3> rand:uniform(1_000_000).
334013
%% Start over with E that may have been stored
%% in ETS, on file, etc...
4> rand:seed(E).
5> rand:uniform(1_000_000).
334013
%% Within the same node this works just as well
6> rand:seed(S).
7> rand:uniform(1_000_000).
334013
```
""".
-doc(#{group => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec export_seed() -> 'undefined' | export_state().
export_seed() ->
case get(?SEED_DICT) of
{#{type:=Alg}, AlgState} -> {Alg, AlgState};
_ -> undefined
end.
-doc """
Export the seed value.
Returns the random number generator state in an external format.
To be used with `seed_s/1`.
#### _Shell Example_
```erlang
%% Initialize a predictable PRNG sequence
1> S0 = rand:seed_s(exsss, 4711).
%% Export the (initial) state
2> E = rand:export_seed_s(S0).
%% Generate an integer N in the interval 1 .. 1_000_000
3> {N, S1} = rand:uniform_s(1_000_000, S0).
4> N.
334013
%% Start over with E that may have been stored
%% in ETS, on file, etc...
5> S2 = rand:seed_s(E).
%% S2 is equivalent to S0
6> {N, S3} = rand:uniform_s(1_000_000, S2).
%% S3 is equivalent to S1
7> N.
334013
%% Within the same node this works just as well
8> {N, S4} = rand:uniform_s(1_000_000, S0).
%% S4 is equivalent to S1
9> N.
334013
```
""".
-doc(#{group => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec export_seed_s(State :: state()) -> export_state().
export_seed_s({#{type:=Alg}, AlgState}) -> {Alg, AlgState}.
%% seed(Alg) seeds RNG with runtime dependent values
%% and return the NEW state
%%
%% seed({Alg,AlgState}) setup RNG with a previously exported seed
%% and return the NEW state
-doc """
Seed the random number generator and select algorithm.
The same as [`seed_s(Alg_or_State)`](`seed_s/1`),
but also stores the generated state in the process dictionary.
The argument `default` is an alias for the
[_default algorithm_](#default-algorithm)
that has been implemented *(Since OTP 24.0)*.
#### _Shell Example_
```erlang
%% Initialize a PRNG sequence
%% with the default algorithm and automatic seed.
%% The return value from rand:seed/1 is normally
%% not used, but here we use it to verify equality
1> S = rand:seed(default).
%% Start from a state exported from
%% the process dictionary is equivalent
2> S = rand:seed(rand:export_seed()).
%% A state can also be used as a start state
3> S = rand:seed(S).
%% With a heavier algorithm
4> SS = rand:seed(exro928ss).
5> SS = rand:seed(rand:export_seed()).
```
""".
-doc(#{group => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec seed(Alg | State) -> state() when
Alg :: builtin_alg() | 'default',
State :: state() | export_state().
seed(Alg_or_State) ->
seed_put(seed_s(Alg_or_State)).
-doc """
Seed the random number generator and select algorithm.
With the argument `Alg`, select that algorithm and seed random number
generation with reasonably unpredictable time dependent data
that should be unique to the created generator instance.
It is (for now) based on the node name, the calling `t:pid/0`,
the system time, and a system unique integer. This set of
fairly unique items may change in the future, if necessary.
`Alg = default` is an alias for the
[_default algorithm_](#default-algorithm)
*(Since OTP 24.0)*.
With the argument `State`, re-creates the state and returns it.
See also `export_seed/0`.
#### _Shell Example_
```erlang
%% Initialize a PRNG sequence
%% with the default algorithm and automatic seed
1> S = rand:seed_s(default).
%% Start from an exported state is equivalent
2> S = rand:seed_s(rand:export_seed_s(S)).
%% A state can also be used as a start state
3> S = rand:seed_s(S).
%% With a heavier algorithm
4> SS = rand:seed_s(exro928ss).
5> SS = rand:seed_s(rand:export_seed_s(SS)).
```
""".
-doc(#{group => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec seed_s(Alg | State) -> state() when
Alg :: builtin_alg() | 'default',
State :: state() | export_state().
seed_s(Alg_or_State) ->
case Alg_or_State of
{AlgHandler, _AlgState} = State when is_map(AlgHandler) ->
State;