Random Numbers in Elixir
In Elixir, we can generate random numbers using the :rand
module. Let’s explore how to use it.
defmodule RandomNumbers do
def main do
# Generate a random integer between 0 and 99 (inclusive)
IO.write(:rand.uniform(100) - 1)
IO.write(",")
IO.puts(:rand.uniform(100) - 1)
# Generate a random float between 0.0 and 1.0
IO.puts(:rand.uniform())
# Generate random floats in the range 5.0 <= f < 10.0
IO.write(5 + :rand.uniform() * 5)
IO.write(",")
IO.puts(5 + :rand.uniform() * 5)
# Create a new random number generator with a known seed
seed1 = {1406, 314159, 271828}
:rand.seed(:exsss, seed1)
IO.write(:rand.uniform(100) - 1)
IO.write(",")
IO.puts(:rand.uniform(100) - 1)
# Create another generator with the same seed
seed2 = {1406, 314159, 271828}
:rand.seed(:exsss, seed2)
IO.write(:rand.uniform(100) - 1)
IO.write(",")
IO.puts(:rand.uniform(100) - 1)
end
end
RandomNumbers.main()
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:
$ elixir random_numbers.exs
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49
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.