Random Numbers in Elixir
In Elixir, we can generate random numbers using the :rand
module. Let’s explore how to use it.
Let’s break down the code and explain its components:
We define a module
RandomNumbers
with amain
function that demonstrates various random number generation techniques.:rand.uniform(100) - 1
generates a random integer between 0 and 99 (inclusive). We subtract 1 because:rand.uniform(n)
returns a number between 1 and n.:rand.uniform()
generates a random float between 0.0 and 1.0.To generate random floats in a specific range (e.g., 5.0 <= f < 10.0), we multiply the result of
:rand.uniform()
by the range size and add the minimum value.To create a random number generator with a known seed, we use
:rand.seed/2
. The first argument is the algorithm (:exsss
in this case), and the second is the seed tuple.We demonstrate that using the same seed produces the same sequence of random numbers.
When you run this program, you might see output similar to this:
Note that the actual numbers may be different when you run the sample, except for the last two lines which should be identical due to using the same seed.
Elixir’s :rand
module provides various other functions for random number generation. You can refer to the Erlang rand module documentation for more information, as Elixir uses Erlang’s random number generation under the hood.