Where to initialize a random seed for use through multiple random modules?

So, every time I develop something big, with several modules coming together to create the final functionality, I am asked a question on the same question: where to initialize a random seed, if more than 1 module you need to use a random function

If I have a specific class that needs a random one (for example, a class that initializes itself by sorting the input array with self-tuning quicksort, so I need a random selection to select), I usually have a private variable static bool isRandOn;, so before I start the selection random selection, I will check this variable and do srand(time(NULL));if a random value is not yet included.

If I have a ton of utility functions in the namespace, I do a very similar thing: I put such a variable in the anonymous namespace inside my utils library and do more or less the same thing as for the class.

The problem is combining these modules. I myself know that each module will not set the seed more than once. But I want to be able to use different modules together, I want other people to be able to use one or more of my modules independently of the others ...

So, what is the best way to handle multiple modules requiring random visits? Install seed in each module? Do not set the seed at all, but instead document the use of random and force the user to initialize the seed if he wants to use the module? Something third?

+3
source share
3 answers

I would suggest using Boost.Random rather than relying on some kind of global state shared at the program level.

Boost.Random has two concepts:

  • Engine: generates random numbers
  • Distributions: which adapt the result from the engines to provide results corresponding to a specific distribution (normal, Poisson, Gaussian, ...)

: , .

: , , , . - ( ).

+1

"" . , .

+1

@penelope . rand(). rand_func(prev_rand), . srand(time(NULL)), prev_rand , , time(NULL) . , srand() ( ) .

, : , srand(0) .. .

0

All Articles