Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Can I seed srand() with results from rand()?

by RollyGuy (Chaplain)
on Jul 10, 2003 at 14:21 UTC ( #272977=note: print w/replies, xml ) Need Help??

in reply to Can I seed srand() with results from rand()?

The rand that perl uses is a PRNG (pseudo random number generator). This loosely means that it is *mostly* random allowing for some predictability. This is where the seed comes in. The seed set up the PRNG in such a way as to produce a set of randoms based on that seed. So, if you were to use a constant seed in a program, then every time the program runs, it will choose the same random values. The following chunk of code is a good example of this:
srand(1); for(0..4){ print rand(10),"\n"; }

Every time you run this code, it will spit out the same values even though we are calling rand. Another way to think about it (abstractly) is that the PRNG is a hash of random sequences and the seed is the key to the hash. Each time you set the key, you are selecting a particular random sequence. Then, each call to rand gets the next value in the set sequence.

This leads us into calling srand multiple times. I do see how calling srand multiple times will help you in your situation, but keep in mind that calling it too often will hurt the randomness of your program. Your solution looks fine if you are willing to sacrifice some randomness.

As far as other solutions go, you've provided one where when you resume, you call rand as many times as you had done up to that point. You've already got overhead of calling srand many times in a loop, so the overhead of calling rand many times when you resume may not be that bad of a tradeoff. You would eliminate two lines from within a loop. You would eliminate the srand calls and the rand calls to generate a new random seed. These would be replaced with a loop on resuming that just calls rand a number of times. This would probably make the resume startup slower, however. It's a tradeoff.

Another solution would be saving extra data. For example, if you run 300 iterations and then must pause, save a random seed. Then when you resume, use the random seed to resume and finish the run. If this run is interesting, then to rerun, you must somehow provide a way to reset the seed 300 iterations into the run. This method will also suffer from not being the same as a run that was not paused/restarted, but you must decide if that is important. Sometimes it really isn't in the end.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2022-11-29 01:20 GMT
Find Nodes?
    Voting Booth?