1rand(3) Erlang Module Definition rand(3)
2
3
4
6 rand - Pseudo random number generation.
7
9 This module provides a pseudo random number generator. The module con‐
10 tains a number of algorithms. The uniform distribution algorithms are
11 based on the Xoroshiro and Xorshift algorithms by Sebastiano Vigna.
12 The normal distribution algorithm uses the Ziggurat Method by
13 Marsaglia and Tsang on top of the uniform distribution algorithm.
14
15 For most algorithms, jump functions are provided for generating non-
16 overlapping sequences for parallel computations. The jump functions
17 perform calculations equivalent to perform a large number of repeated
18 calls for calculating new states.
19
20 The following algorithms are provided:
21
22 exsss:
23 Xorshift116**, 58 bits precision and period of 2^116-1
24
25 Jump function: equivalent to 2^64 calls
26
27 This is the Xorshift116 generator combined with the StarStar scram‐
28 bler from the 2018 paper by David Blackman and Sebastiano Vigna:
29 Scrambled Linear Pseudorandom Number Generators
30
31 The generator does not need 58-bit rotates so it is faster than the
32 Xoroshiro116 generator, and when combined with the StarStar scram‐
33 bler it does not have any weak low bits like exrop (Xoroshiro116+).
34
35 Alas, this combination is about 10% slower than exrop, but is de‐
36 spite that the default algorithm thanks to its statistical quali‐
37 ties.
38
39 exro928ss:
40 Xoroshiro928**, 58 bits precision and a period of 2^928-1
41
42 Jump function: equivalent to 2^512 calls
43
44 This is a 58 bit version of Xoroshiro1024**, from the 2018 paper by
45 David Blackman and Sebastiano Vigna: Scrambled Linear Pseudorandom
46 Number Generators that on a 64 bit Erlang system executes only
47 about 40% slower than the defaultexsssalgorithm but with much
48 longer period and better statistical properties, but on the flip
49 side a larger state.
50
51 Many thanks to Sebastiano Vigna for his help with the 58 bit adap‐
52 tion.
53
54 exrop:
55 Xoroshiro116+, 58 bits precision and period of 2^116-1
56
57 Jump function: equivalent to 2^64 calls
58
59 exs1024s:
60 Xorshift1024*, 64 bits precision and a period of 2^1024-1
61
62 Jump function: equivalent to 2^512 calls
63
64 exsp:
65 Xorshift116+, 58 bits precision and period of 2^116-1
66
67 Jump function: equivalent to 2^64 calls
68
69 This is a corrected version of the previous default algorithm,
70 that now has been superseded by Xoroshiro116+ (exrop). Since there
71 is no native 58 bit rotate instruction this algorithm executes a
72 little (say < 15%) faster than exrop. See the algorithms' homepage.
73
74 The current default algorithm is exsss (Xorshift116**). If a specific
75 algorithm is required, ensure to always use seed/1 to initialize the
76 state.
77
78 Which algorithm that is the default may change between Erlang/OTP re‐
79 leases, and is selected to be one with high speed, small state and
80 "good enough" statistical properties.
81
82 Undocumented (old) algorithms are deprecated but still implemented so
83 old code relying on them will produce the same pseudo random sequences
84 as before.
85
86 Note:
87 There were a number of problems in the implementation of the now undoc‐
88 umented algorithms, which is why they are deprecated. The new algo‐
89 rithms are a bit slower but do not have these problems:
90
91 Uniform integer ranges had a skew in the probability distribution that
92 was not noticable for small ranges but for large ranges less than the
93 generator's precision the probability to produce a low number could be
94 twice the probability for a high.
95
96 Uniform integer ranges larger than or equal to the generator's preci‐
97 sion used a floating point fallback that only calculated with 52 bits
98 which is smaller than the requested range and therefore were not all
99 numbers in the requested range even possible to produce.
100
101 Uniform floats had a non-uniform density so small values i.e less than
102 0.5 had got smaller intervals decreasing as the generated value ap‐
103 proached 0.0 although still uniformly distributed for sufficiently
104 large subranges. The new algorithms produces uniformly distributed
105 floats on the form N * 2.0^(-53) hence equally spaced.
106
107
108 Every time a random number is requested, a state is used to calculate
109 it and a new state is produced. The state can either be implicit or be
110 an explicit argument and return value.
111
112 The functions with implicit state use the process dictionary variable
113 rand_seed to remember the current state.
114
115 If a process calls uniform/0, uniform/1 or uniform_real/0 without set‐
116 ting a seed first, seed/1 is called automatically with the default al‐
117 gorithm and creates a non-constant seed.
118
119 The functions with explicit state never use the process dictionary.
120
121 Examples:
122
123 Simple use; creates and seeds the default algorithm with a non-constant
124 seed if not already done:
125
126 R0 = rand:uniform(),
127 R1 = rand:uniform(),
128
129 Use a specified algorithm:
130
131 _ = rand:seed(exs928ss),
132 R2 = rand:uniform(),
133
134 Use a specified algorithm with a constant seed:
135
136 _ = rand:seed(exs928ss, {123, 123534, 345345}),
137 R3 = rand:uniform(),
138
139 Use the functional API with a non-constant seed:
140
141 S0 = rand:seed_s(exsss),
142 {R4, S1} = rand:uniform_s(S0),
143
144 Textbook basic form Box-Muller standard normal deviate
145
146 R5 = rand:uniform_real(),
147 R6 = rand:uniform(),
148 SND0 = math:sqrt(-2 * math:log(R5)) * math:cos(math:pi() * R6)
149
150 Create a standard normal deviate:
151
152 {SND1, S2} = rand:normal_s(S1),
153
154 Create a normal deviate with mean -3 and variance 0.5:
155
156 {ND0, S3} = rand:normal_s(-3, 0.5, S2),
157
158 Note:
159 The builtin random number generator algorithms are not cryptographi‐
160 cally strong. If a cryptographically strong random number generator is
161 needed, use something like crypto:rand_seed/0.
162
163
164 For all these generators except exro928ss and exsss the lowest bit(s)
165 has got a slightly less random behaviour than all other bits. 1 bit for
166 exrop (and exsp), and 3 bits for exs1024s. See for example the explana‐
167 tion in the Xoroshiro128+ generator source code:
168
169 Beside passing BigCrush, this generator passes the PractRand test suite
170 up to (and included) 16TB, with the exception of binary rank tests,
171 which fail due to the lowest bit being an LFSR; all other bits pass all
172 tests. We suggest to use a sign test to extract a random Boolean value.
173
174 If this is a problem; to generate a boolean with these algorithms use
175 something like this:
176
177 (rand:uniform(16) > 8)
178
179 And for a general range, with N = 1 for exrop, and N = 3 for exs1024s:
180
181 (((rand:uniform(Range bsl N) - 1) bsr N) + 1)
182
183 The floating point generating functions in this module waste the lowest
184 bits when converting from an integer so they avoid this snag.
185
187 builtin_alg() =
188 exsss | exro928ss | exrop | exs1024s | exsp | exs64 |
189 exsplus | exs1024
190
191 alg() = builtin_alg() | atom()
192
193 alg_handler() =
194 #{type := alg(),
195 bits => integer() >= 0,
196 weak_low_bits => integer() >= 0,
197 max => integer() >= 0,
198 next :=
199 fun((alg_state()) -> {integer() >= 0, alg_state()}),
200 uniform => fun((state()) -> {float(), state()}),
201 uniform_n =>
202 fun((integer() >= 1, state()) -> {integer() >= 1, state()}),
203 jump => fun((state()) -> state())}
204
205 alg_state() =
206 exsplus_state() |
207 exro928_state() |
208 exrop_state() |
209 exs1024_state() |
210 exs64_state() |
211 term()
212
213 state() = {alg_handler(), alg_state()}
214
215 Algorithm-dependent state.
216
217 export_state() = {alg(), alg_state()}
218
219 Algorithm-dependent state that can be printed or saved to file.
220
221 seed() =
222 [integer()] | integer() | {integer(), integer(), integer()}
223
224 A seed value for the generator.
225
226 A list of integers sets the generator's internal state directly,
227 after algorithm-dependent checks of the value and masking to the
228 proper word size. The number of integers must be equal to the
229 number of state words in the generator.
230
231 An integer is used as the initial state for a SplitMix64 genera‐
232 tor. The output values of that is then used for setting the gen‐
233 erator's internal state after masking to the proper word size
234 and if needed avoiding zero values.
235
236 A traditional 3-tuple of integers seed is passed through algo‐
237 rithm-dependent hashing functions to create the generator's ini‐
238 tial state.
239
240 exsplus_state()
241
242 Algorithm specific internal state
243
244 exro928_state()
245
246 Algorithm specific internal state
247
248 exrop_state()
249
250 Algorithm specific internal state
251
252 exs1024_state()
253
254 Algorithm specific internal state
255
256 exs64_state()
257
258 Algorithm specific internal state
259
261 bytes(N :: integer() >= 0) -> Bytes :: binary()
262
263 Returns, for a specified integer N >= 0, a binary() with that
264 number of random bytes. Generates as many random numbers as re‐
265 quired using the selected algorithm to compose the binary, and
266 updates the state in the process dictionary accordingly.
267
268 bytes_s(N :: integer() >= 0, State :: state()) ->
269 {Bytes :: binary(), NewState :: state()}
270
271 Returns, for a specified integer N >= 0 and a state, a binary()
272 with that number of random bytes, and a new state. Generates as
273 many random numbers as required using the selected algorithm to
274 compose the binary, and the new state.
275
276 export_seed() -> undefined | export_state()
277
278 Returns the random number state in an external format. To be
279 used with seed/1.
280
281 export_seed_s(State :: state()) -> export_state()
282
283 Returns the random number generator state in an external format.
284 To be used with seed/1.
285
286 jump() -> NewState :: state()
287
288 Returns the state after performing jump calculation to the state
289 in the process dictionary.
290
291 This function generates a not_implemented error exception when
292 the jump function is not implemented for the algorithm specified
293 in the state in the process dictionary.
294
295 jump(State :: state()) -> NewState :: state()
296
297 Returns the state after performing jump calculation to the given
298 state.
299
300 This function generates a not_implemented error exception when
301 the jump function is not implemented for the algorithm specified
302 in the state.
303
304 normal() -> float()
305
306 Returns a standard normal deviate float (that is, the mean is 0
307 and the standard deviation is 1) and updates the state in the
308 process dictionary.
309
310 normal(Mean :: number(), Variance :: number()) -> float()
311
312 Returns a normal N(Mean, Variance) deviate float and updates the
313 state in the process dictionary.
314
315 normal_s(State :: state()) -> {float(), NewState :: state()}
316
317 Returns, for a specified state, a standard normal deviate float
318 (that is, the mean is 0 and the standard deviation is 1) and a
319 new state.
320
321 normal_s(Mean :: number(),
322 Variance :: number(),
323 State0 :: state()) ->
324 {float(), NewS :: state()}
325
326 Returns, for a specified state, a normal N(Mean, Variance) devi‐
327 ate float and a new state.
328
329 seed(AlgOrStateOrExpState ::
330 builtin_alg() | state() | export_state()) ->
331 state()
332
333 seed(Alg :: default) -> state()
334
335 Seeds random number generation with the specifed algorithm and
336 time-dependent data if AlgOrStateOrExpState is an algorithm. Alg
337 = default is an alias for the default algorithm.
338
339 Otherwise recreates the exported seed in the process dictionary,
340 and returns the state. See also export_seed/0.
341
342 seed(Alg :: builtin_alg(), Seed :: seed()) -> state()
343
344 seed(Alg :: default, Seed :: seed()) -> state()
345
346 Seeds random number generation with the specified algorithm and
347 integers in the process dictionary and returns the state. Alg =
348 default is an alias for the default algorithm.
349
350 seed_s(AlgOrStateOrExpState ::
351 builtin_alg() | state() | export_state()) ->
352 state()
353
354 seed_s(Alg :: default) -> state()
355
356 Seeds random number generation with the specifed algorithm and
357 time-dependent data if AlgOrStateOrExpState is an algorithm. Alg
358 = default is an alias for the default algorithm.
359
360 Otherwise recreates the exported seed and returns the state. See
361 also export_seed/0.
362
363 seed_s(Alg :: builtin_alg(), Seed :: seed()) -> state()
364
365 seed_s(Alg :: default, Seed :: seed()) -> state()
366
367 Seeds random number generation with the specified algorithm and
368 integers and returns the state. Alg = default is an alias for
369 the default algorithm.
370
371 uniform() -> X :: float()
372
373 Returns a random float uniformly distributed in the value range
374 0.0 =< X < 1.0 and updates the state in the process dictionary.
375
376 The generated numbers are on the form N * 2.0^(-53), that is;
377 equally spaced in the interval.
378
379 Warning:
380 This function may return exactly 0.0 which can be fatal for cer‐
381 tain applications. If that is undesired you can use (1.0 -
382 rand:uniform()) to get the interval 0.0 < X =< 1.0, or instead
383 use uniform_real/0.
384
385 If neither endpoint is desired you can test and re-try like
386 this:
387
388 my_uniform() ->
389 case rand:uniform() of
390 0.0 -> my_uniform();
391 X -> X
392 end
393 end.
394
395
396 uniform_real() -> X :: float()
397
398 Returns a random float uniformly distributed in the value range
399 DBL_MIN =< X < 1.0 and updates the state in the process dictio‐
400 nary.
401
402 Conceptually, a random real number R is generated from the in‐
403 terval 0 =< R < 1 and then the closest rounded down normalized
404 number in the IEEE 754 Double precision format is returned.
405
406 Note:
407 The generated numbers from this function has got better granu‐
408 larity for small numbers than the regular uniform/0 because all
409 bits in the mantissa are random. This property, in combination
410 with the fact that exactly zero is never returned is useful for
411 algoritms doing for example 1.0 / X or math:log(X).
412
413
414 See uniform_real_s/1 for more explanation.
415
416 uniform(N :: integer() >= 1) -> X :: integer() >= 1
417
418 Returns, for a specified integer N >= 1, a random integer uni‐
419 formly distributed in the value range 1 =< X =< N and updates
420 the state in the process dictionary.
421
422 uniform_s(State :: state()) -> {X :: float(), NewState :: state()}
423
424 Returns, for a specified state, random float uniformly distrib‐
425 uted in the value range 0.0 =< X < 1.0 and a new state.
426
427 The generated numbers are on the form N * 2.0^(-53), that is;
428 equally spaced in the interval.
429
430 Warning:
431 This function may return exactly 0.0 which can be fatal for cer‐
432 tain applications. If that is undesired you can use (1.0 -
433 rand:uniform(State)) to get the interval 0.0 < X =< 1.0, or in‐
434 stead use uniform_real_s/1.
435
436 If neither endpoint is desired you can test and re-try like
437 this:
438
439 my_uniform(State) ->
440 case rand:uniform(State) of
441 {0.0, NewState} -> my_uniform(NewState);
442 Result -> Result
443 end
444 end.
445
446
447 uniform_real_s(State :: state()) ->
448 {X :: float(), NewState :: state()}
449
450 Returns, for a specified state, a random float uniformly dis‐
451 tributed in the value range DBL_MIN =< X < 1.0 and updates the
452 state in the process dictionary.
453
454 Conceptually, a random real number R is generated from the in‐
455 terval 0 =< R < 1 and then the closest rounded down normalized
456 number in the IEEE 754 Double precision format is returned.
457
458 Note:
459 The generated numbers from this function has got better granu‐
460 larity for small numbers than the regular uniform_s/1 because
461 all bits in the mantissa are random. This property, in combina‐
462 tion with the fact that exactly zero is never returned is useful
463 for algoritms doing for example 1.0 / X or math:log(X).
464
465
466 The concept implicates that the probability to get exactly zero
467 is extremely low; so low that this function is in fact guaran‐
468 teed to never return zero. The smallest number that it might re‐
469 turn is DBL_MIN, which is 2.0^(-1022).
470
471 The value range stated at the top of this function description
472 is technically correct, but 0.0 =< X < 1.0 is a better descrip‐
473 tion of the generated numbers' statistical distribution. Except
474 that exactly 0.0 is never returned, which is not possible to ob‐
475 serve statistically.
476
477 For example; for all sub ranges N*2.0^(-53) =< X <
478 (N+1)*2.0^(-53) where 0 =< integer(N) < 2.0^53 the probability
479 is the same. Compare that with the form of the numbers generated
480 by uniform_s/1.
481
482 Having to generate extra random bits for small numbers costs a
483 little performance. This function is about 20% slower than the
484 regular uniform_s/1
485
486 uniform_s(N :: integer() >= 1, State :: state()) ->
487 {X :: integer() >= 1, NewState :: state()}
488
489 Returns, for a specified integer N >= 1 and a state, a random
490 integer uniformly distributed in the value range 1 =< X =< N and
491 a new state.
492
493
494
495Ericsson AB stdlib 3.17.2 rand(3)