Tags

,

In erlang, random isn’t always random. Purists will claim that pseudo random number generators are never truly random, so who cares. Possibly, but this is less theoretical and more about implementation.

The first is a bug to be fixed in R14 (but not R14A, which is a shame). Basically if any of the three elements in the seed tuple are 0, then your seed never changes. If you happen to use now() as your seed, then occasionally you’ll see duplicate results

The second is related to randomness and processes. My empirical tests after a bout of head banging indicate that the seed is local to the process in which random:uniform is called.

14> spawn(fun() -> io:format("Random: ~p~n", [random:uniform(10000)]) end).
Random: 924
<0.49.0>
15> spawn(fun() -> io:format("Random: ~p~n", [random:uniform(10000)]) end).
Random: 924
<0.51.0>
16> spawn(fun() -> io:format("Random: ~p~n", [random:uniform(10000)]) end).
Random: 924
<0.53.0>
17> spawn(fun() -> io:format("Random: ~p~n", [random:uniform(10000)]) end).
Random: 924
<0.55.0>
18> spawn(fun() -> random:seed(now()), io:format("Random: ~p~n", [random:uniform(10000)]) end).
Random: 148
<0.57.0>
19> spawn(fun() -> random:seed(now()), io:format("Random: ~p~n", [random:uniform(10000)]) end).
Random: 1785
<0.59.0>

So kids, the moral of this story is to seed often and mind your zeroes.

Notes

Shout out to will for the link to this comic.

Advertisements