rand(3erl)
πΈ NAME πΈ
rand β pseudo random number generation, but make it a whole moment.
Okay bestie, welcome to rand(3erl) from the Erlang Module Definition manual β¨ this is the module you call when you need numbers that are random-ish and you need them now. Like, it literally does what it says on the tin: pseudo random number generation. Let's get into it π
π DESCRIPTION π
So this module hands you a pseudo random number generator, and it's not just one algorithm β it's a whole little roster π«Ά The uniform distribution algorithms are built on the Xoroshiro and Xorshift algorithms by Sebastiano Vigna. The normal distribution algorithm uses the Ziggurat Method by Marsaglia and Tsang, layered right on top of the uniform distribution algorithm.
For most algorithms, there are also jump functions for generating non-overlapping sequences so you can do parallel computations. The jump functions do the equivalent of performing a large number of repeated calls for calculating new states β but they run in a time roughly equivalent to one regular iteration per generator bit. So like, same destination, way shorter flight βοΈ
And heads up: at the end of this module documentation there are also some niche algorithms to be used without this module's normal plug-in framework API β useful for special purposes like short generation time when quality is not essential, for seeding other generators, and such. Little side quests, iykyk.
π The algorithms, ranked by yours truly π
exsss
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.
The generator does not need 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 is despite that the default algorithm thanks to its statistical qualities. Slower but slay-ier, we love a queen with standards.
exro928ss
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 β that on a 64 bit Erlang system executes only about 40% slower than the default exsss 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 π«Ά icon behaviour honestly.
exrop
Xoroshiro116+, 58 bits precision and period of 2^116-1.
Jump function: equivalent to 2^64 calls.
exs1024s
Xorshift1024*, 64 bits precision and a period of 2^1024-1.
Jump function: equivalent to 2^512 calls.
exsp
Xorshift116+, 58 bits precision and period of 2^116-1.
Jump function: equivalent to 2^64 calls.
This is a corrected version of the previous default algorithm, that now has been superseded by Xoroshiro116+ (exrop). Since there is no native 58 bit rotate instruction this algorithm executes a little (say < 15%) faster than exrop. See the algorithms' homepage.
π The default situation π
The current default algorithm is exsss (Xorshift116**). If a specific algorithm is required, ensure to always use seed/1 to initialize the state. No cap, do the seeding.
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.
Undocumented (old) algorithms are deprecated but still implemented so old code relying on them will produce the same pseudo random sequences as before. Nostalgia, but make it backwards compatible π
β οΈ Note: why the old ones are deprecated β οΈ
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. Rude.
- 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 were not all numbers in the requested range even possible to produce. Literally unreachable numbers π
- Uniform floats had a non-uniform density so small values i.e 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 equally spaced. Equally spaced is the vibe πΈ
π¦ State, implicit vs explicit π¦
Every time a random number is requested, a state is used to calculate it and a new state is produced. The state can either be implicit or be an explicit argument and return value.
The functions with implicit state use the process dictionary variable rand_seed to remember the current state.
If a process calls uniform/0, uniform/1 or uniform_real/0 without setting a seed first, seed/1 is called automatically with the default algorithm and creates a non-constant seed. It's giving self-care, the module seeds itself π
The functions with explicit state never use the process dictionary. Not once. Zero notes.
β¨ Examples (the good stuff) β¨
Simple use; creates and seeds the default algorithm with a non-constant seed if not already done:
R0 = rand:uniform(),
R1 = rand:uniform(),
Use a specified algorithm:
_ = rand:seed(exs928ss),
R2 = rand:uniform(),
Use a specified algorithm with a constant seed:
_ = rand:seed(exs928ss, {123, 123534, 345345}),
R3 = rand:uniform(),
Use the functional API with a non-constant seed:
S0 = rand:seed_s(exsss),
{R4, S1} = rand:uniform_s(S0),
Textbook basic form Box-Muller standard normal deviate:
R5 = rand:uniform_real(),
R6 = rand:uniform(),
SND0 = math:sqrt(-2 * math:log(R5)) * math:cos(math:pi() * R6)
Create a standard normal deviate:
{SND1, S2} = rand:normal_s(S1),
Create a normal deviate with mean -3 and variance 0.5:
{ND0, S3} = rand:normal_s(-3, 0.5, S2),
π Note (important, bestie, read this one): 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. Do not use these to generate your passwords, I'm begging π
π Note (the low-bits situation): For all these generators exceptexro928ssandexsssthe lowest bit(s) has got a slightly less random behaviour than all other bits. 1 bit forexrop(andexsp), and 3 bits forexs1024s. See for example the explanation in the Xoroshiro128+ 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:
(rand:uniform(256) > 128) % -> boolean()
((rand:uniform(256) - 1) bsr 7) % -> 0 | 1
For a general range, with N = 1 for exrop, and N = 3 for exs1024s:
(((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. Problem? Solved. Periodt π
π DATA TYPES π
builtin_alg()
builtin_alg() =
exsss | exro928ss | exrop | exs1024s | exsp | exs64 |
exsplus | exs1024 | dummy
alg()
alg() = builtin_alg() | atom()
alg_handler()
alg_handler() =
#{type := alg(),
bits => integer() >= 0,
weak_low_bits => integer() >= 0,
max => integer() >= 0,
next :=
fun((alg_state()) -> {integer() >= 0, alg_state()}),
uniform => fun((state()) -> {float(), state()}),
uniform_n =>
fun((integer() >= 1, state()) -> {integer() >= 1, state()}),
jump => fun((state()) -> state())}
alg_state()
alg_state() =
exsplus_state() |
exro928_state() |
exrop_state() |
exs1024_state() |
exs64_state() |
dummy_state() |
term()
state()
state() = {alg_handler(), alg_state()}
Algorithm-dependent state. It's the little bundle of algorithm + state, matching set π
export_state()
export_state() = {alg(), alg_state()}
Algorithm-dependent state that can be printed or saved to file. Screenshot it, print it, frame it, whatever πΌοΈ
seed()
seed() =
[integer()] | integer() | {integer(), integer(), integer()}
A seed value for the generator. Three flavours, pick your fighter:
- 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.
- An integer is used as the initial state for a SplitMix64 generator. The 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.
exsplus_state()
Algorithm specific internal state.
exro928_state()
Algorithm specific internal state.
exrop_state()
Algorithm specific internal state.
exs1024_state()
Algorithm specific internal state.
exs64_state()
Algorithm specific internal state.
dummy_state()
dummy_state() = uint58()
Algorithm specific internal state.
splitmix64_state()
splitmix64_state() = uint64()
Algorithm specific state.
uint58()
uint58() = 0..288230376151711743
0 .. (2^58 - 1) β yes, that's the range, and yes, we're including it for the record β
uint64()
uint64() = 0..18446744073709551615
0 .. (2^64 - 1) β the big one, the whole 64-bit buffet π₯
mwc59_state()
mwc59_state() = 1..574882961707499518
1 .. ((16#1ffb072 * 2^29 - 1) - 1) β niche, mysterious, iconic π¦
π PLUG-IN FRAMEWORK API π
β¨ EXPORTS β¨
okay bestie, here comes the whole menu of functions π every single one, no skipping, and yes I'm gonna tell you what each one actually does.
π bytes/1
bytes(N :: integer() >= 0) -> Bytes :: binary()
gives you a binary() that's exactly N bytes long, for any integer N >= 0. It keeps generating random numbers with whichever algorithm you picked until the binary is full, and updates the state in the process dictionary as it goes. it's giving "here's your bag of random bytes, enjoy" π«Ά
π bytes_s/2
bytes_s(N :: integer() >= 0, State :: state()) ->
{Bytes :: binary(), NewState :: state()}
same vibe as bytes/1 but you hand it a state and it hands you back both the binary() (still N bytes, N >= 0) and the fresh new state. it does the same "generate as many random numbers as needed with the selected algorithm" thing β just without touching the process dictionary. love that for us β¨
π export_seed/0
export_seed() -> undefined | export_state()
hands you the random number state in an external format. like putting your RNG state in a little travel case π§³ intended to be used with seed/1.
π export_seed_s/1
export_seed_s(State :: state()) -> export_state()
same travel-case energy, but for the state you pass in. also meant to be used with seed/1.
π jump/0
jump() -> NewState :: state()
does the jump calculation on the state in the process dictionary and gives you back the new state. iconic for splitting a stream of randomness into independent streams π
β οΈ but bestie β if the jump function isn't implemented for whatever algorithm that state is using, this throws a not_implemented error exception. so. heads up π
π jump/1
jump(State :: state()) -> NewState :: state()
the same jump calculation, except you give it the state instead of it digging one out of the process dictionary. returns the new state.
β οΈ same deal: not_implemented error exception if the algorithm in that state has no jump function. no cap π
π normal/0
normal() -> float()
returns a standard normal deviate float β mean 0, standard deviation 1 β and updates the state in the process dictionary. bell curve princess behavior π¦
π normal/2
normal(Mean :: number(), Variance :: number()) -> float()
same but you pick the Mean and Variance, and it gives you a normal N(Mean, Variance) deviate float (and updates the process-dictionary state, obviously).
π normal_s/1
normal_s(State :: state()) -> {float(), NewState :: state()}
for a given state: a standard normal deviate float (mean 0, std dev 1) plus the shiny new state. π
π normal_s/3
normal_s(Mean :: number(),
Variance :: number(),
State0 :: state()) ->
{float(), NewS :: state()}
for a given state: a normal N(Mean, Variance) deviate float plus a new state. three-arg excellence, we love to see it π
π seed/1
seed(AlgOrStateOrExpState ::
builtin_alg() | state() | export_state()) ->
state()
seed(Alg :: default) -> state()
seeds random number generation. if AlgOrStateOrExpState is an algorithm, it seeds using that algorithm plus time-dependent data β° and Alg = default is just an alias for the default algorithm.
otherwise (so: you passed a state or an exported state) it recreates the exported seed in the process dictionary and returns the state. see also export_seed/0 π«Ά
π seed/2
seed(Alg :: builtin_alg(), Seed :: seed()) -> state()
seed(Alg :: default, Seed :: seed()) -> state()
seeds random number generation with the specified algorithm and the integers you give it, in the process dictionary, and returns the state. again, Alg = default is an alias for the default algorithm β¨
π seed_s/1
seed_s(AlgOrStateOrExpState ::
builtin_alg() | state() | export_state()) ->
state()
seed_s(Alg :: default) -> state()
the state-returning, process-dictionary-free sibling of seed/1. if you give it an algorithm, it seeds with that algorithm and time-dependent data. Alg = default = alias for the default algorithm.
otherwise it recreates the exported seed and returns the state. see also export_seed/0 π§
π seed_s/2
seed_s(Alg :: builtin_alg(), Seed :: seed()) -> state()
seed_s(Alg :: default, Seed :: seed()) -> state()
seeds with the specified algorithm and integers, and returns the state. and yep β Alg = default is an alias for the default algorithm. consistent queen π
π uniform/0
uniform() -> X :: float()
returns a random float, uniformly distributed so that 0.0 =< X < 1.0, and updates the state in the process dictionary. the generated numbers are on the form N * 2.0^(-53), meaning they're equally spaced across the interval π
β οΈ Warning: this can return exactly0.0, and that can be fatal for some applications. if that's not the vibe you can use(1.0 - rand:uniform())to get the interval0.0 < X =< 1.0, or just useuniform_real/0instead. and if you want neither endpoint, test and re-try like this:
my_uniform() ->
case rand:uniform() of
0.0 -> my_uniform();
X -> X
end
end.
π uniform_real/0
uniform_real() -> X :: float()
returns a random float uniformly distributed in DBL_MIN =< X < 1.0 and updates the state in the process dictionary.
conceptually: a random real number R gets generated from the interval 0 =< R < 1, and then you get back the closest rounded-down normalized number in the IEEE 754 Double precision format. very demure, very precise π
β¨ Note: the numbers from this one have better granularity for small numbers than regularuniform/0, because all the bits in the mantissa are random. that property, plus the fact that it never returns exactly zero, is super useful for algorithms doing stuff like1.0 / Xormath:log(X). seeuniform_real_s/1for more explanation π«Ά
π uniform/1
uniform(N :: integer() >= 1) -> X :: integer() >= 1
for an integer N >= 1: a random integer uniformly distributed in 1 =< X =< N, and updates the process-dictionary state. dice roll era π²
π uniform_s/1
uniform_s(State :: state()) -> {X :: float(), NewState :: state()}
for a given state: a random float uniformly distributed in 0.0 =< X < 1.0 plus a new state. numbers are on the form N * 2.0^(-53), equally spaced in the interval.
β οΈ Warning: this may return exactly0.0, which can be fatal for certain applications. if that's not it, use(1.0 - rand:uniform(State))for the interval0.0 < X =< 1.0, or useuniform_real_s/1instead. if neither endpoint is your thing, test and re-try like so:
my_uniform(State) ->
case rand:uniform(State) of
{0.0, NewState} -> my_uniform(NewState);
Result -> Result
end
end.
π uniform_real_s/1
uniform_real_s(State :: state()) ->
{X :: float(), NewState :: state()}
for a given state: a random float uniformly distributed in DBL_MIN =< X < 1.0, and it updates the state in the process dictionary.
conceptually, a random real number R comes from 0 =< R < 1, and then the closest rounded-down normalized number in IEEE 754 Double precision gets returned.
β¨ Note: these numbers have better granularity for small numbers than regularuniform_s/1because all the mantissa bits are random. combined with never returning exactly zero, that's great for algorithms doing1.0 / Xormath:log(X). the concept means the probability of getting exactly zero is extremely low β so low that this function is in fact guaranteed to never return zero. the smallest number it might return isDBL_MIN, which is2.0^(-1022). the value range at the top of this description is technically correct, but0.0 =< X < 1.0is a better description of the statistical distribution of the generated numbers β except that exactly0.0is never returned, which you couldn't observe statistically anyway π for example: for all sub rangesN*2.0^(-53) =< X < (N+1)*2.0^(-53)where0 =< integer(N) < 2.0^53, the probability is the same. compare that to the form of the numbers generated byuniform_s/1π having to generate extra random bits for small numbers costs a little performance β this function is about 20% slower than the regularuniform_s/1. a small price, bestie π
π uniform_s/2
uniform_s(N :: integer() >= 1, State :: state()) ->
{X :: integer() >= 1, NewState :: state()}
for an integer N >= 1 and a state: a random integer uniformly distributed in 1 =< X =< N, plus a new state. the stateful dice roll, and that's a wrap on this section πβ¨
β¨ NICHE ALGORITHMS API β¨
Okay bestie, this section is for the special-purpose algorithms β the ones that do not use the plug-in framework API, usually because speed is the whole point π₯.
Since these algorithms lack plug-in framework support, generating numbers in a range other than the generator's own generated range may become a problem. Lowkey a whole situation π.
There are at least 3 ways to do this, assuming that the range is less than the generator's range:
π Modulo
To generate a number V in the range 0..Range-1:
- Generate a number X.
- Use
V = X rem Rangeas 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. Not the vibe π« .
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, that is; 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
To generate a number V in the range 0..Range-1, when you have a generator with the range 0..2^Bits-1:
- Generate a number X.
- Use
V = X*Range bsr Bitsas 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 method above.
π Shift or mask
To generate a number in the range 0..2^RBits-1, when you have a generator with the range 0..2^Bits:
- Generate a number X.
- Use
V = X band ((1 bsl RBits)-1)orV = 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. Choose wisely bestie π
.
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 method above.
π« Rejection
- Generate a number X.
- If X is in the range, use
V = Xas 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. She persists π.
These methods can be combined, such as using the Modulo method and only if the generator value would create bias use Rejection. Or using Shift or mask to reduce the size of a generator value so that Truncated multiplication 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. Slay, math icon behavior β¨.
π« splitmix64_next/1
splitmix64_next(AlgState :: integer()) ->
{X :: uint64(),
NewAlgState :: splitmix64_state()}
okay so this one hands you back a random 64-bit integer X and a shiny new generator state NewAlgState, following the SplitMix64 algorithm. β¨
the rand module uses this generator internally to seed other generators, and that's genuinely iconic of it β it's a completely different breed of generator, which lowkey lowers the odds of accidentally cooking up a bad seed. π
πΈ exsp_next/1
exsp_next(AlgState :: exsplus_state()) ->
{X :: uint58(), NewAlgState :: exsplus_state()}
gives you a random 58-bit integer X and the fresh state NewAlgState, per the Xorshift116+ algorithm. π
this is an API function that reaches straight into the internal implementation of the exsp algorithm, so you can use it without the overhead of the plug-in framework β super handy for time-critical applications, no cap. on a typical 64-bit Erlang VM this approach runs in just above 30% (1/3) of the time the default algorithm takes through this module's normal plug-in framework. β‘
to seed this generator, use {_, AlgState} = rand:seed_s(exsp) or {_, AlgState} = rand:seed_s(exsp, Seed) with a specific Seed.
Note: this function gives you zero help generating a number on a selected range, and zero help with floating point numbers. it is so easy to accidentally mess up this generator's pretty good statistical properties when doing either. see the recipes at the start of this Niche algorithms API description. also clock the caveat about weak low bits that this generator suffers from. it's exported in this form primarily for performance β iykyk. π
π¦ exsp_jump/1
exsp_jump(AlgState :: exsplus_state()) ->
NewAlgState :: exsplus_state()
returns a new generator state that's equivalent to the state you'd have after iterating exsp_next/1 2^64 times. yes, that many. π«Ά
see the description of jump functions at the top of this module description for the full lore.
π mwc59/1
mwc59(CX0 :: mwc59_state()) -> CX1 :: mwc59_state()
returns a new generator state CX1 per a Multiply With Carry generator β which is a very efficient implementation of a Multiplicative Congruential Generator with a power of 2 multiplier and a prime modulus. main character math fr fr. β¨
this generator uses the multiplier 2^32 and the modulus 16#7fa6502 * 2^32 - 1, both selected in collaboration with Sebastiano Vigna to dodge bignum operations while still serving good statistical quality. it can be written as:
C = CX0 bsr 32
X = CX0 band ((1 bsl 32)-1))
CX1 = 16#7fa6502 * X + C
because the generator uses a multiplier that's a power of 2, it picks up statistical flaws for collision tests and birthday spacings tests in 2 and 3 dimensions β and even these caveats apply only to the MWC "digit", that is the low 32 bits (due to the multiplier) of the generator state. π
the quality of the output value improves a lot by using a scrambler instead of just grabbing the low bits. mwc59_value32 is a fast scrambler that returns a decent 32-bit number. the slightly slower mwc59_value scrambler returns 59 bits of very good quality, and mwc59_float returns a float() of very good quality. π
the low bits of the base generator are surprisingly good, so the lowest 16 bits actually pass fairly strict PRNG tests, despite the generator's weaknesses living up in the high bits of the 32-bit MWC "digit". it's recommended to use rem on the generator state, or a bit mask extracting the lowest bits, to produce numbers in a range of 16 bits or less. see the recipes at the start of this Niche algorithms API description. π
on a typical 64-bit Erlang VM this generator runs in below 8% (1/13) of the time the default algorithm takes in the plug-in framework API of this module. with the mwc59_value32 scrambler the total time becomes 16% (1/6), and with mwc59_value it becomes 20% (1/5) of the default algorithm's time. with mwc59_float the total time is 60% of the time for the default algorithm generating a float().
Note: this is a niche generator for high speed applications. it has a much shorter period than the default generator, which is itself a quality concern β although when used with the value scramblers it does pass strict PRNG tests. it's much faster than exsp_next/1 but with a bit lower quality. π
π mwc59_value32/1
mwc59_value32(CX :: mwc59_state()) -> V :: 0..4294967295
returns a 32-bit value V from a generator state CX. the state gets scrambled with an 8-bit xorshift, which masks the statistical imperfections of the base generator mwc59 enough to produce numbers of decent quality. some problems in 2- and 3-dimensional birthday spacing and collision tests still show through, though. π
when you use this scrambler it's generally better to use the high bits of the value than the low. the lowest 8 bits are of good quality and pass right through from the base generator; they get combined with the next 8 in the xorshift, which makes the low 16 good quality β but in the range 16..31 bits there are weaker bits that you do not want sitting as the high bits of your generated values. so it's generally safer to shift out low bits. see the recipes at the start of this Niche algorithms API description. π§
for a non power of 2 range less than about 16 bits (so you don't get too much bias and you avoid bignums), truncated multiplication can be used β it's much faster than rem: (Range*V) bsr 32.
β mwc59_value/1
mwc59_value(CX :: mwc59_state()) -> V :: 0..576460752303423487
returns a 59-bit value V from a generator state CX. the state is scrambled using a 4-bit followed by a 27-bit xorshift, which masks the statistical imperfections of the base generator mwc59 enough that all 59 bits come out of very good quality. π
be careful not to accidentally create a bignum when handling the value V. π
it's generally better to use the high bits from this scrambler than the low. see the recipes at the start of this Niche algorithms API description.
for a non power of 2 range less than about 29 bits (again: not too much bias, no bignums), truncated multiplication can be used β much faster than rem. example for range 1'000'000'000: the range is 30 bits, so we use 29 bits from the generator, adding up to 59 bits, which is not a bignum:
(1000000000 * (V bsr (59-29))) bsr 29
π mwc59_float/1
mwc59_float(CX :: mwc59_state()) -> V :: float()
returns the generator value V from a generator state CX, as a float(). the state gets scrambled exactly like with mwc59_value/1 before it's converted to a float(). slay. π
π mwc59_seed/0 and mwc59_seed/1
mwc59_seed() -> CX :: mwc59_state()
mwc59_seed(S :: 0..288230376151711743) -> CX :: mwc59_state()
both return a generator state CX. S is hashed to create the generator state, so that similar seeds don't create similar sequences β obsessed with that design choice honestly. πΈ
without S, the generator state is created as for seed_s(atom()).
okay bestie that's literally the whole page!! π you just read the entire rand(3erl) man page from Ericsson AB, stdlib 4.3.1.3 β go forth and generate random numbers responsibly, mwah π β¨ π«Ά
π¦ where this page comes from
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4 Β· Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms