in reply to Legacy code uses "srand()" .. how to avoid losing entropy?

Why not just re-seed the RNG after whatever requires a known seed?
srand($known_thing); # code relying on $known_thing srand(0);
Sure, you get a different stream of random numbers, but it's just as random as the one you had before. Heck, you could even make it a function:
sub with_srand { srand(shift); $_[0]->(@_[1..$#_]); srand(); } # later with_srand $known_thing, sub { ... }, args...;

Replies are listed 'Best First'.
Re^2: Legacy code uses "srand()" .. how to avoid losing entropy?
by locked_user sundialsvc4 (Abbot) on May 04, 2011 at 12:30 UTC

    I do not see clear documentation of what srand(0) is supposed to do (in e.g. Perl 5.10.0).   If perldoc srand on my system says it, I missed it twice.

    However, it clearly does have the following blunt caveats:

    Do not call srand() (i.e. without an argument) more than once in a script.   The internal state of the random number generator should contain more entropy than can be provided by any seed, so calling srand() again actually loses randomness.

    and ...

    Most implementations of srand take an integer and will silently truncate decimal numbers.   This means srand(42) will usually produce the same results as srand(42.1).   To be safe, always pass srand an integer.

    (Emphasis theirs.)

    The strategy I am looking at is more or less like this:

    my $random_now = rand();

    srand($repeatable_seed);
    (insert repeatable code here)

    srand(MAXINT * $random_now);

    Although it remains that “the internal state of the random number generator (will) contain (less) entropy,” it seems to be the best available compromise, at least with the versions of Perl that are available to me for this purpose, and it involves a small and focused set of code changes.

    In the long run, of course, I am going to scrap this technique altogether.   I will generate a random sequence of numbers and then simply store that sequence for re-use.   But this legacy-code system is very much in service all across the country right now.   I must dance on eggshells.