Erlang Central

Random Numbers Seeding

Revision as of 23:11, 3 September 2006 by Bfulgham (Talk | contribs)

Problem

You notice that several processes are getting the same "random" number sequence. You would like each process to be receiving its own unique random numbers.

Solution

Use the random:seed function to seed the pseudo-random number generator with a new seed value.

1> random:seed().    % Default seed from process dictionary
{5815,21695,596}
2> random:seed(5991,29821,991).
{3172,9814,20125}

The pseudo-random number generator used in the Erlang implementation defaults to a constant value in the current process dictionary. Consequently, processes that happen to start at the same time could potentially seed with the same value. Using the random:seed function allows you to modify this default behavior.

Seeding a pseudo-random number generator sets its internal state deterministically. Seeding a generator with a particular number forces it to produce a sequence of pseudo-random numbers that is the same across runs and across platforms. This could be useful if you wish to provide the illusion of randomness.