Search code examples
c++crandomsrand

Usefulness of `rand()` - or who should call `srand()`?


Background: I use rand(), std::rand(), std::random_shuffle() and other functions in my code for scientific calculations. To be able to reproduce my results, I always explicitly specify the random seed, and set it via srand(). That worked fine until recently, when I figured out that libxml2 would also call srand() lazily on its first usage - which was after my early srand() call.

I filled in a bug report to libxml2 about its srand() call, but I got the answer:

Initialize libxml2 first then. That's a perfectly legal call to be made from a library. You should not expect that nobody else calls srand(), and the man page nowhere states that using srand() multiple time should be avoided

This is actually my question now. If the general policy is that every lib can/should/will call srand(), and I can/might also call it here and there, I don't really see how that can be useful at all. Or how is rand() useful then?

That is why I thought, the general (unwritten) policy is that no lib should ever call srand() and the application should call it only once in the beginning. (Not taking multi-threading into account. I guess in that case, you anyway should use something different.)

I also tried to research a bit which other libraries actually call srand(), but I didn't find any. Are there any?

My current workaround is this ugly code:

{
    // On the first call to xmlDictCreate,
    // libxml2 will initialize some internal randomize system,
    // which calls srand(time(NULL)).
    // So, do that first call here now, so that we can use our
    // own random seed.
    xmlDictPtr p = xmlDictCreate();
    xmlDictFree(p);
}

srand(my_own_seed);

Probably the only clean solution would be to not use that at all and only to use my own random generator (maybe via C++11 <random>). But that is not really the question. The question is, who should call srand(), and if everyone does it, how is rand() useful then?


Solution

  • Use the new <random> header instead. It allows for multiple engine instances, using different algorithms and more importantly for you, independent seeds.

    [edit] To answer the "useful" part, rand generates random numbers. That's what it's good for. If you need fine-grained control, including reproducibility, you should not only have a known seed but a known algorithm. srand at best gives you a fixed seed, so that's not a complete solution anyway.