Pseudo-random generation in EO
EO library provides an ability to generate pseudo-random sequences. It’s analogous to Random class in Java or random module in Python. Let’s explore how this facility (exposed via org.eolang.math.random object) can be used in EO.
The random object
has been available in the eo.lang.math package since version 0.1.2. It decorates float
and represents a value from a random sequence.
Note that the generator is pseudo-random. In short, it means that the generated sequence can be reproduced given an initial seed value, which is not what true randomness normally assumes. In most applied cases, pseudo-randomness is perfectly enough. Hereafter the terms random and pseudo-random will be used interchangeably.
A single random value can be generated as follows:
+alias org.eolang.math.random
[args...] > app
QQ.io.stdout > @
QQ.txt.sprintf
"Random value is %f"
random.pseudo
Here the random.pseudo object represents a float object with a random value
in the range 0..1 (0 included, 1 excluded).
An array of 5 random values can be generated like this:
[args...] > app
random.pseudo > rnd!
reduce. > @
list (* 1 2 3 4 5)
*
[a i]
a.with rnd.next > @
In this case, the first call to rnd generates a new random object. Each consecutive call to
rnd.next produces the next float value in the random sequence. Values produced by random.next
are normally distributed in the range 0..1. Under the hood, random.next uses
the linear congruential method to
generate the next random element.
The initial seed can be used to reproduce the sequence of values generated by random.next:
[args...] > equal-app
eq. > @
(random 3142).next.next.next.next
(random 3142).next.next.next.next
In this example, equal-app will evaluate to TRUE. Moreover, corresponding elements
(i.e. produced by the same number of next calls) of both sequences will be equal.
However, in the following snippet different initial seeds will generate different sequences:
[args...] > not-equal-app
eq. > @
(random 5938).next.next.next.next
(random 3142).next.next.next.next
Read more on Random Generation on the Wiki page.