A random number is a number chosen at random from a given distribution. Selecting a large number of them reproduces the underlying distribution.
Elixir lacks a module to produce random numbers. However, it can use underlying Erlang
modules like rand
(now favored over random
) or crypto
to select random items from enumerables
.
We should note that :rand.uniform(n)
returns integers. Enum.random
's documentation also claims that it can effectively generate random numbers by choosing a value at random from the range limit.
This allows us to create integers inside range bounds without traversing the entire range.
We use the :rand.uniform(n)
method to generate random numbers in Elixir.
:rand.uniform(n)
The :rand.uniform(n)
receives a number/integer n
as a parameter, which represents a range of 0
to n
. For example, if we want a random number between 0 and 50, we pass in n = 50
.
Note: The given range is inclusive of
0
andn
.
# prints a random numberrandom_number = :rand.uniform(256)IO.inspect random_number
Line 2: We create a variable random_number
, where we use :rand.uniform(256)
. This selects a random number between 0 and 256, and passes it to the random_number
variable.
Line 3: We use IO.inspect
to generate the output.
Let’s run the code above to see the output as it generates a random number.