My teacher told me the only way to have random non-correlated numbers in awk between consecutive runs of the same script, is saving the last seed used to file and then read it again when you start another execution.
So far I'm trying with this:
BEGIN {
getline seed < "myseed.txt";
srand(seed);
print rand();
print rand();
print srand() > "myseed.txt";
}
but the only content of myseed.txt
is always 0 and I get the same random numbers at every execution.
Any ideas on how to save the status of the internal random number generator and then resuming generating random numbers exactly where it stopped between different executions of the same script?
There seems to be some confusion about what the seed actually is. It's a value used as a parameter to initialize the random number generator, and that's it; it does not contain the current state of the random number generator. If you call srand(N)
with any N, and then generate some random numbers, and then call srand()
again (with any seed), the return value will be that original N, no matter how many random numbers you have generated in the meantime.
If the goal is to have a reproducible string of numbers, allowing for interruptions, then you need to save not only the seed but the number of random numbers generated so far since the seeding, and generate and discard that many at the start of the next run. This is a terrible hack and you would probably be better implementing your own RNG or, more likely, using something other than awk.
If the goal is to make sure not to generate the same sequence even if run twice within a single second, then you should read the discussion at the link Ed Morton posted in his comment.