Want to contribute? Fork us in GitHub!

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.

random object available in eo.lang.math package since version 0.1.2. It decorates float and represents a value from random sequence.

Note that the generator is pseudo-random. In short, it means that generated sequence can be reproduced given initial seed value which is not what true randomness normally assumes.
In most applied cases pseudo-randomness is perfectly enough. Hereafter terms random and pseudo-random will be used interchangeably.

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 random.pseudo object represents float object with random value in 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 first call to rnd generates new random object. Each consecutive call to rnd.next produces next float value in random sequence. Values produced by random.next are normally distributed in range 0..1. Under the hood random.next uses Linear congruential method to generate next random element.

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. produces 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

More on Random Generation read on Wiki page