dimanche 2 juillet 2017

Random numbers in C++11: is there a simple way to seed the generator in one place of the code, then use it in different functions?

Before C++11, I used rand() from <cstdlib> and it was very simple to choose to seed (or not) the generator in the main() function (for example), then use in libraryA random numbers generated by a function somewhere in libraryB. The code looked like this:

LibraryB (generates random numbers, old-fashioned way):

#include <cstdlib> // rand, RAND_MAX
double GetRandDoubleBetween0And1() {
   return ((double)rand()) / ((double)RAND_MAX);
}

Main program:

#include <cstdlib> // srand
#include <ctime> // time, clock
void main() {
   bool iWantToSeed = true; // or false,
                            // decide HERE, applies everywhere!
   if(iWantToSeed){
      srand((unsigned)time(0) + (unsigned int)clock());
   }
   // (...)
}

LibraryA (uses random numbers from LibraryB, generated according to the seed given in main()):

#include "../folderOfLibraryB/Utils_random.h" // GetRandDoubleBetween0And1
void UseSomeRandomness(){
   for(int i = 0; i < 1000000; i++){
      double nb = GetRandDoubleBetween0And1();
      // (...)
   }
}

Easy, right?

Now I want to update GetRandDoubleBetween0And1() using the C++11 standards available via #include <random>. I have already read and seen the examples here and there, but I don't see how to adapt it to my three modules. Surely, seeding the engine each time GetRandDoubleBetween0And1() is called is not the right thing to do...

Do you think I will have to pass the seeded engine from main() to UseSomeRandomness() in LibraryA, then from UseSomeRandomness() to GetRandDoubleBetween0And1() in LibraryB? Or is there a simpler way?

Aucun commentaire:

Enregistrer un commentaire