Random Numbers in Erlang

The rand module in Erlang provides pseudorandom number generation.

-module(random_numbers).
-export([main/0]).

main() ->
    % For example, rand:uniform(N) returns a random integer X, where 1 =< X =< N.
    io:format("~p,~p~n", [rand:uniform(100), rand:uniform(100)]),

    % rand:uniform() returns a random float F, where 0.0 =< F < 1.0.
    io:format("~p~n", [rand:uniform()]),

    % This can be used to generate random floats in other ranges, for example 5.0 =< F' < 10.0.
    io:format("~p,~p~n", [5 + rand:uniform() * 5, 5 + rand:uniform() * 5]),

    % If you want a known seed, create a new rand state using rand:seed/1.
    % Here we use the 'exs1024' algorithm with a fixed seed.
    State1 = rand:seed(exs1024, {1, 2, 3}),
    {NewValue1, _} = rand:uniform_s(100, State1),
    {NewValue2, _} = rand:uniform_s(100, State1),
    io:format("~p,~p~n", [NewValue1, NewValue2]),

    % Using the same seed will produce the same sequence of random numbers.
    State2 = rand:seed(exs1024, {1, 2, 3}),
    {NewValue3, _} = rand:uniform_s(100, State2),
    {NewValue4, _} = rand:uniform_s(100, State2),
    io:format("~p,~p~n", [NewValue3, NewValue4]).

To run the program:

$ erlc random_numbers.erl
$ erl -noshell -s random_numbers main -s init stop
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

Some of the generated numbers may be different when you run the sample.

The rand module in Erlang provides various functions for random number generation. You can refer to the Erlang documentation for more information on other random quantities that Erlang can provide.