|Think about Loose Coupling|
Can I seed srand() with results from rand()?by blokhead (Monsignor)
|on Jul 10, 2003 at 01:46 UTC||Need Help??|
blokhead has asked for the wisdom of the Perl Monks concerning the following question:
I'm performing a lengthy computation that uses a lot of calls to rand, and I want to be able to pause the computation and resume it again later (using Storable or some other serialization). The process starts with a random seed that I provide, so that I can reproduce interesting results later. I want the results to be the same for a given initial random seed regardless of whether I paused/resumed the computation, so I need to somehow save a random seed in my serialization.
The only reasonable* solution I could think of was something along these lines:
I use rand to generate a new seed for the next iteration, so it can be saved after any iteration. As soon as I wrote srand inside my while loop, red flags popped up in my head. The srand perldoc says:
Do not call srand() multiple times in your program unless you know exactly what you're doing and why you're doing it.... but I wonder if I really know exactly what I'm doing ;). I found at least one post regarding multiple srand calls, but in that case the poster was using something like time ^ $$ to re-seed within a very fast loop, and expecting different random output for each loop.
What I would really like to know is in what situations is ok to call srand multiple times? Is using a call to rand for a seed considered bad? I can't use any external entropy to re-seed, because I want all the results to be based on the original random seed supplied at the beginning of the computation. Any thoughts on the serialization of randomly-generated state data like this?
*: In the worst case I could always wrap rand, save the original random seed, and simply save the number of times rand was called. Then to resume again, I just reseed, and call rand in void context a whole slug of times. I'd rather not do this!