Skip to content

Commit 1bf9b3d

Browse files
Merge pull request #11165 from RaimoNiskanen/raimo/stdlib/rand-default-seed/OTP-20158
Improve default seed to spread out the entropy over all 3 words
2 parents 67582db + a74b351 commit 1bf9b3d

1 file changed

Lines changed: 13 additions & 3 deletions

File tree

lib/stdlib/src/rand.erl

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1006,9 +1006,19 @@ seed_s(Alg_or_State) ->
10061006
end.
10071007

10081008
default_seed() ->
1009-
{erlang:phash2([{node(),self()}]),
1010-
erlang:system_time(),
1011-
erlang:unique_integer()}.
1009+
%% The purpose of this seed is that it shall be different
1010+
%% for different calls in a cluster even if they coincide in time.
1011+
%% High entropy is hard to find and not a primary goal.
1012+
%%
1013+
%% Luckily self() in external term format contains the node name
1014+
%% so the seed will differ between nodes as well as between processes.
1015+
%% unique_integer makes the seed differ between calls. system_time
1016+
%% gives some more entropy. MD5 is used to spread out the entropy
1017+
%% over all 3 seed integers.
1018+
%%
1019+
SeedTerm = {self(), erlang:unique_integer(), erlang:system_time()},
1020+
<<A:43, B:43, C:42>> = erlang:md5(term_to_binary(SeedTerm)),
1021+
{A, B, C}.
10121022

10131023
%% seed/2: seeds RNG with the algorithm and given values
10141024
%% and returns the NEW state.

0 commit comments

Comments
 (0)