-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
rand.erl
2858 lines (2521 loc) · 109 KB
/
rand.erl
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%
%%
%% Copyright Ericsson AB 2015-2024. 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. Most are provided through
a [plug-in framework](#plug-in-framework) that adds
features to the base generators.
At the end of this module documentation there are some
[niche algorithms](#niche-algorithms) that don't use
this module's normal [plug-in framework](#plug-in-framework).
They may be useful for special purposes like short generation time
when quality is not essential, for seeding other generators, and such.
[](){: #plug-in-framework } Plug-in framework
---------------------------------------------
The [plug-in framework](#plug-in-framework-api) implements
a common [API](#plug-in-framework-api) to, and enhancements
of the base generators:
* Operating on a generator state in the
[process dictionary](#generator-state).
* [Automatic](#generator-state) [seeding](`seed/1`).
* Manual [seeding support](`seed/2`) to avoid common pitfalls.
* Generating [integers](`t:integer/0`) in any range, with
[uniform distribution](`uniform/1`), without noticable bias.
* Generating [integers](`t:integer/0`) in any range, larger than
the base generator's, with [uniform distribution](`uniform/1`).
* Generating [floating-point numbers](`t:float/0`) with
[uniform distribution](`uniform/0`).
* Generating [floating-point numbers](`t:float/0`) with
[normal distribution](`normal/0`).
* Generating any number of [bytes](`bytes/1`).
The base generator algorithms implements the
[Xoroshiro and Xorshift algorithms](http://xorshift.di.unimi.it)
by Sebastiano Vigna. During an iteration they generate a large integer
(at least 58-bit) and operate on a state of several large integers.
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.
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.
[](){: #algorithms } 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 doesn't use 58-bit rotates so it is faster than the
Xoroshiro116 generator, and when combined with the StarStar scrambler
it doesn't 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
- **`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
doesn't use rotate 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.
Which algorithm that is the default may change between Erlang/OTP releases,
and is selected to be one with high speed, small state and "good enough"
statistical properties.
#### 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 noticable 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 weren't 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
> on the form `N * 2.0^(-53)` hence they are equally spaced.
[](){: #generator-state }
#### Generator State
Every time a random number is generated, a state is used to calculate it,
producing a new state. The state can either be implicit
or be an explicit argument and return value.
The functions with implicit state operates on a state stored
in the process dictionary under the key `rand_seed`. If that key
doesn't exist when the function is called, `seed/1` is called automatically
with the [_default algorithm_](#default-algorithm) and creates
a reasonably unpredictable seed.
The functions with explicit state don't use the process dictionary.
#### _Examples_
Simple use; create and seed the
[_default algorithm_](#default-algorithm) with a non-fixed seed,
if not already done, and generate two uniformly distibuted
floating point numbers.
```erlang
R0 = rand:uniform(),
R1 = rand:uniform(),
```
Use a specified algorithm:
```erlang
_ = rand:seed(exs928ss),
R2 = rand:uniform(),
```
Use a specified algorithm with a fixed seed:
```erlang
_ = rand:seed(exs928ss, {123, 123534, 345345}),
R3 = rand:uniform(),
```
Use the functional API with a non-fixed seed:
```erlang
S0 = rand:seed_s(exsss),
{R4, S1} = rand:uniform_s(S0),
```
Generate a textbook basic form Box-Muller standard normal distribution number:
```erlang
R5 = rand:uniform_real(),
R6 = rand:uniform(),
SND0 = math:sqrt(-2 * math:log(R5)) * math:cos(math:pi() * R6)
```
Generate a standard normal distribution number:
```erlang
{SND1, S2} = rand:normal_s(S1),
```
Generate a normal distribution number with with mean -3 and variance 0.5:
```erlang
{ND0, S3} = rand:normal_s(-3, 0.5, S2),
```
#### 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 something like `crypto:rand_seed/0`.
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 don't use the
[plug-in framework](#plug-in-framework), mainly for performance reasons.
Since these algorithms lack the plug-in framework support, generating numbers
in 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` in 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 the base generator is a full length generator,
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 * (1.0/((1 bsl 53)))` as your value.
This will create a value on the form N*2^-53 with equal probability
for every possible N for the range.
""".
-moduledoc(#{since => "OTP 18.0",
titles =>
[{function,<<"Plug-in framework API">>},
{function,<<"Niche algorithms API">>}]}).
-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
]).
%% 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,
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).
%% =====================================================================
%% 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 plugins.
%%
%% 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() ::
#{type := alg(),
bits => non_neg_integer(),
weak_low_bits => non_neg_integer(),
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())}.
%% 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 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.
A single integer is used as the initial state for a SplitMix64 generator.
The sequential output values of that is then used for setting
the generator's internal state after masking to the proper word size
and if needed avoiding zero values.
A traditional 3-tuple of integers seed is passed through algorithm-dependent
hashing functions to create the generator's initial state.
""".
-type seed() :: [integer()] | integer() | {integer(), integer(), integer()}.
-export_type(
[builtin_alg/0, alg/0, alg_handler/0, 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`.
""".
-doc(#{title => <<"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/1`.
""".
-doc(#{title => <<"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)*.
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec seed(Alg_or_State :: term()) -> 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.
`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`.
""".
-doc(#{title => <<"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({AlgHandler, _AlgState} = State) when is_map(AlgHandler) ->
State;
seed_s({Alg, AlgState}) when is_atom(Alg) ->
{AlgHandler,_SeedFun} = mk_alg(Alg),
{AlgHandler,AlgState};
seed_s(Alg) ->
seed_s(Alg, default_seed()).
default_seed() ->
{erlang:phash2([{node(),self()}]),
erlang:system_time(),
erlang:unique_integer()}.
%% seed/2: seeds RNG with the algorithm and given values
%% and returns the NEW state.
-doc """
Seed the random number generator and select algorithm.
The same as [`seed_s(Alg, Seed)`](`seed_s/2`),
but also stores the generated state in the process dictionary.
`Alg = default` is an alias for the
[_default algorithm_](#default-algorithm)
that has been implemented *(Since OTP 24.0)*.
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec seed(Alg :: term(), Seed :: term()) -> state().
seed(Alg, Seed) ->
seed_put(seed_s(Alg, Seed)).
-doc """
Seed the random number generator and select algorithm.
Creates and returns a generator state for the specified algorithm
from the specified `t:seed/0` integers.
`Alg = default` is an alias for the [_default algorithm_](#default-algorithm)
that has been implemented *since OTP 24.0*.
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec seed_s(Alg, Seed) -> state() when
Alg :: builtin_alg() | 'default',
Seed :: seed().
seed_s(default, Seed) -> seed_s(?DEFAULT_ALG_HANDLER, Seed);
seed_s(Alg, Seed) ->
{AlgHandler,SeedFun} = mk_alg(Alg),
AlgState = SeedFun(Seed),
{AlgHandler,AlgState}.
%%% uniform/0, uniform/1, uniform_s/1, uniform_s/2 are all
%%% uniformly distributed random numbers.
%% uniform/0: returns a random float X where 0.0 =< X < 1.0,
%% updating the state in the process dictionary.
-doc """
Generate a uniformly distributed random number `0.0 =< X < 1.0`,
using the state in the process dictionary.
Like `uniform_s/1` but operates on the state stored in
the process dictionary. Returns the generated number `X`.
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec uniform() -> X :: float().
uniform() ->
{X, State} = uniform_s(seed_get()),
_ = seed_put(State),
X.
%% uniform/1: given an integer N >= 1,
%% uniform/1 returns a random integer X where 1 =< X =< N,
%% updating the state in the process dictionary.
-doc """
Generate a uniformly distributed random integer `1 =< X =< N`,
using the state in the process dictionary.
Like `uniform_s/2` but operates on the state stored in
the process dictionary. Returns the generated number `X`.
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec uniform(N :: pos_integer()) -> X :: pos_integer().
uniform(N) ->
{X, State} = uniform_s(N, seed_get()),
_ = seed_put(State),
X.
%% uniform_s/1: given a state, uniform_s/1
%% returns a random float X where 0.0 =< X < 1.0,
%% and a new state.
-doc """
Generate a uniformly distributed random number `0.0 =< X < 1.0`.
From the specified `State`, generates a random number `X ::` `t:float/0`,
uniformly distributed in the value range `0.0 =< X < 1.0`.
Returns the number `X` and the updated `NewState`.
The generated numbers are on the form `N * 2.0^(-53)`, that is;
equally spaced in the interval.
> #### Warning {: .warning }
>
> This function may return exactly `0.0` which can be fatal for certain
> applications. If that is undesired you can use `(1.0 - rand:uniform())`
> to get the interval `0.0 < X =< 1.0`, or instead use `uniform_real/0`.
>
> If neither endpoint is desired you can achieve the range
> `0.0 < X < 1.0` using test and re-try like this:
>
> ```erlang
> my_uniform() ->
> case rand:uniform() of
> X when 0.0 < X -> X;
> _ -> my_uniform()
> end.
> ```
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec uniform_s(State :: state()) -> {X :: float(), NewState :: state()}.
uniform_s(State = {#{uniform:=Uniform}, _}) ->
Uniform(State);
uniform_s({#{bits:=Bits, next:=Next} = AlgHandler, R0}) ->
{V, R1} = Next(R0),
%% Produce floats on the form N * 2^(-53)
{(V bsr (Bits - 53)) * ?TWO_POW_MINUS53, {AlgHandler, R1}};
uniform_s({#{max:=Max, next:=Next} = AlgHandler, R0}) ->
{V, R1} = Next(R0),
%% Old algorithm with non-uniform density
{V / (Max + 1), {AlgHandler, R1}}.
%% uniform_s/2: given an integer N >= 1 and a state, uniform_s/2
%% uniform_s/2 returns a random integer X where 1 =< X =< N,
%% and a new state.
-doc """
Generate a uniformly distributed random integer `1 =< X =< N`.
From the specified `State`, generates a random number `X ::` `t:integer/0`,
uniformly distributed in the specified range `1 =< X =< N`.
Returns the number `X` and the updated `NewState`.
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 18.0">>}).
-spec uniform_s(N :: pos_integer(), State :: state()) ->
{X :: pos_integer(), NewState :: state()}.
uniform_s(N, State = {#{uniform_n:=UniformN}, _})
when is_integer(N), 1 =< N ->
UniformN(N, State);
uniform_s(N, {#{bits:=Bits, next:=Next} = AlgHandler, R0})
when is_integer(N), 1 =< N ->
{V, R1} = Next(R0),
MaxMinusN = ?BIT(Bits) - N,
?uniform_range(N, AlgHandler, R1, V, MaxMinusN, I);
uniform_s(N, {#{max:=Max, next:=Next} = AlgHandler, R0})
when is_integer(N), 1 =< N ->
%% Old algorithm with skewed probability
%% and gap in ranges > Max
{V, R1} = Next(R0),
if
N =< Max ->
{(V rem N) + 1, {AlgHandler, R1}};
true ->
F = V / (Max + 1),
{trunc(F * N) + 1, {AlgHandler, R1}}
end.
%% uniform_real/0: returns a random float X where 0.0 < X =< 1.0,
%% updating the state in the process dictionary.
-doc """
Generate a uniformly distributed random number `0.0 < X < 1.0`,
using the state in the process dictionary.
Like `uniform_real_s/1` but operates on the state stored in
the process dictionary. Returns the generated number `X`.
See `uniform_real_s/1`.
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 21.0">>}).
-spec uniform_real() -> X :: float().
uniform_real() ->
{X, Seed} = uniform_real_s(seed_get()),
_ = seed_put(Seed),
X.
%% uniform_real_s/1: given a state, uniform_s/1
%% returns a random float X where 0.0 < X =< 1.0,
%% and a new state.
%%
%% This function doesn't use the same form of uniformity
%% as the uniform_s/1 function.
%%
%% Instead, this function doesn't generate numbers with equal
%% distance in the interval, but rather tries to keep all mantissa
%% bits random also for small numbers, meaning that the distance
%% between possible numbers decreases when the numbers
%% approaches 0.0, as does the possibility for a particular
%% number. Hence uniformity is preserved.
%%
%% To generate 56 bits at the time instead of 53 is actually
%% a speed optimization since the probability to have to
%% generate a second word decreases by 1/2 for every extra bit.
%%
%% This function generates normalized numbers, so the smallest number
%% that can be generated is 2^-1022 with the distance 2^-1074
%% to the next to smallest number, compared to 2^-53 for uniform_s/1.
%%
%% This concept of uniformity should work better for applications
%% where you need to calculate 1.0/X or math:log(X) since those
%% operations benefits from larger precision approaching 0.0,
%% and that this function doesn't return 0.0 nor denormalized
%% numbers very close to 0.0. The log() operation in The Box-Muller
%% transformation for normal distribution is an example of this.
%%
%%-define(TWO_POW_MINUS55, (math:pow(2, -55))).
%%-define(TWO_POW_MINUS110, (math:pow(2, -110))).
%%-define(TWO_POW_MINUS55, 2.7755575615628914e-17).
%%-define(TWO_POW_MINUS110, 7.7037197775489436e-34).
%%
-doc """
Generate a uniformly distributed random number `0.0 < X < 1.0`.
From the specified state, generates a random float, uniformly distributed
in the value range `DBL_MIN =< X < 1.0`.
Conceptually, a random real number `R` is generated from the interval
`0.0 =< R < 1.0` and then the closest rounded down nonzero
normalized number in the IEEE 754 Double Precision Format is returned.
> #### Note {: .info }
>
> The generated numbers from this function has got better granularity
> for small numbers than the regular `uniform_s/1` because all bits
> in the mantissa are random. This property, in combination with the fact
> that exactly zero is never returned is useful for algorithms doing
> for example `1.0 / X` or `math:log(X)`.
The concept implicates that the probability to get exactly zero is extremely
low; so low that this function in fact never returns `0.0`.
The smallest number that it might return is `DBL_MIN`,
which is `2.0^(-1022)`.
The value range stated at the top of this function description is
technically correct, but `0.0 =< X < 1.0` is a better description
of the generated numbers' statistical distribution, and that
this function never returns exactly `0.0` is impossible to observe.
For all sub ranges `N*2.0^(-53) =< X < (N+1)*2.0^(-53)` where
`0 =< integer(N) < 2.0^53`, the probability to generate a number
in the range is the same. Compare with the numbers
generated by `uniform_s/1`.
Having to generate extra random bits for occasional small numbers
costs a little performance. This function is about 20% slower
than the regular `uniform_s/1`
""".
-doc(#{title => <<"Plug-in framework API">>,since => <<"OTP 21.0">>}).
-spec uniform_real_s(State :: state()) -> {X :: float(), NewState :: state()}.
uniform_real_s({#{bits:=Bits, next:=Next} = AlgHandler, R0}) ->
%% Generate a 56 bit number without using the weak low bits.
%%
%% Be sure to use only 53 bits when multiplying with
%% math:pow(2.0, -N) to avoid rounding which would make
%% "even" floats more probable than "odd".
%%
{V1, R1} = Next(R0),
M1 = V1 bsr (Bits - 56),
if
?BIT(55) =< M1 ->
%% We have 56 bits - waste 3
{(M1 bsr 3) * math:pow(2.0, -53), {AlgHandler, R1}};
?BIT(54) =< M1 ->
%% We have 55 bits - waste 2
{(M1 bsr 2) * math:pow(2.0, -54), {AlgHandler, R1}};
?BIT(53) =< M1 ->
%% We have 54 bits - waste 1
{(M1 bsr 1) * math:pow(2.0, -55), {AlgHandler, R1}};
?BIT(52) =< M1 ->
%% We have 53 bits - use all
{M1 * math:pow(2.0, -56), {AlgHandler, R1}};
true ->
%% Need more bits
{V2, R2} = Next(R1),
uniform_real_s(AlgHandler, Next, M1, -56, R2, V2, Bits)
end;
uniform_real_s({#{max:=_, next:=Next} = AlgHandler, R0}) ->
%% Generate a 56 bit number.
%% Ignore the weak low bits for these old algorithms,
%% just produce something reasonable.
%%
%% Be sure to use only 53 bits when multiplying with
%% math:pow(2.0, -N) to avoid rounding which would make
%% "even" floats more probable than "odd".
%%
{V1, R1} = Next(R0),
M1 = ?MASK(56, V1),
if
?BIT(55) =< M1 ->
%% We have 56 bits - waste 3
{(M1 bsr 3) * math:pow(2.0, -53), {AlgHandler, R1}};
?BIT(54) =< M1 ->