Home > Blockchain >  How much can I change code to keep rand() giving same output for given seed?
How much can I change code to keep rand() giving same output for given seed?

Time:04-07

I'm implementing an algorithm. Because calculations takes time, and I need to repeat them multiple times, I'm saving to output file seed values as well. The idea was that I could repeat same instance of a program if I'll need to get more info about what was happening (like additional values, some percentage, anything that will not mess in the algorithm itself).

Unfortunately, even though I thought everything worked as intended, about 20% of the seeded instances gave different values in at least one of the outputted values.

My question is - what type of changes in the code affects how srand() / rand() works in C ? Each class is compiled separately and all are linked together at the end. Can I implement functions and everything will be fine? Does it break only when I change the size of any class in the program by adding/removing class fields? Is it connected with heap/stack allocation?

Until now, I thought that if I seed srand() I will have same order of rand() values no matter what (eg. for srand(123) I'll always get first rand() == 5, second rand() == 8 etc.). And I can break it only when I'll put more rand() calls in between.

I hope you could find where I'm thinking wrong, or you could link something that will help me.

Cheers mrozo

CodePudding user response:

Your understanding about srand is correct: seeding with a specific value should be enough to generate a reproducible sequence of random numbers. You should debug your application to discover why it behaves in a non-reproducible way.

One reason for such behavior is a race condition on the hidden RNG state. Quoting from the C rand wiki:

It is implementation-defined whether rand() is thread-safe.

...

It is recommended to use C 11's random number generation facilities to replace rand().

  • Related