Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^4: Legacy code uses "srand()" .. how to avoid losing entropy?

by furry_marmot (Pilgrim)
on May 03, 2011 at 17:45 UTC ( #902750=note: print w/ replies, xml ) Need Help??


in reply to Re^3: Legacy code uses "srand()" .. how to avoid losing entropy?
in thread Legacy code uses "srand()" .. how to avoid losing entropy?

It sounds like you're getting wrapped up in a few problems:

  1. You've got code that depends on a stable list of pseudo-random numbers.
  2. The pseudo-random numbers aren't random enough and the results are skewed.
  3. There are calls to srand($n) throughout the program.
  4. You want to capture the "state" of the RNG at various points.

So tackle these problems separately. As a kludge, you should be able to make the program run as-is, but with better results.

  1. Follow JavaFan's (and others') suggestion and pre-generate a list of better random numbers. There are more elegant ways to do this, but for the sake of the concept, store a list of a million pre-generated random numbers in the __DATA__ section of the code, pull them up from <DATA> and put them in a global array @RAND, accessed with a global $COUNTER. External sources might complicate matters at this stage, which is why I suggest throwing it in the code.
  2. Then borrow Tye's suggestion to override srand and rand for your purposes:
    BEGIN { our @RAND = (); our $COUNTER = 0; for (<DATA>) { $_ += 0; push @RAND, $_; } *CORE::GLOBAL::srand = sub(;$){ $COUNTER = 0 }; *CORE::GLOBAL::rand = sub(){ return $RAND[$COUNTER++] }; }
  3. Now srand($n) will ignore $n, but will reset $COUNTER so the sequence can start again. And rand will act as expected, but will return the number from @RAND rather than generate it on the fly. From the perspective of the rest of the code, this should be transparent, obviating the need for global changes (as in search/replace) to the code.
  4. To capture the state of the "RNG" (now a list), simply capture $COUNTER to pick up where you left off later.

--marmot


Comment on Re^4: Legacy code uses "srand()" .. how to avoid losing entropy?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://902750]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (12)
As of 2014-08-01 08:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (257 votes), past polls