Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using one random engine for multi distributions in c++11

Tags:

c++

random

c++11

I am using c++11 new <random> header in my application and in one class in different methods I need different random number with different distributions. I just put a random engine std::default_random_engine as class member seed it in the class constructor with std::random_device and use it for different distributions in my methods. Is that OK to use the random engine in this way or I should declare different engines for every distribution I use.

like image 280
AMCoded Avatar asked Mar 26 '12 10:03

AMCoded


2 Answers

It's ok.

Reasons to not share the generator:

  • threading (standard RNG implementations are not thread safe)
  • determinism of random sequences:

    If you wish to be able (for testing/bug hunting) to control the exact sequences generated, you will by likely have fewer troubles by isolating the RNGs used, especially when not all RNGs consumption is deterministic.

like image 145
sehe Avatar answered Oct 01 '22 06:10

sehe


You should be careful when using one pseudo random number generator for different random variables, because in doing so they become correlated.

Here is an example: If you want to simulate Brownian motion in two dimensions (e.g. x and y) you need randomness in both dimensions. If you take the random numbers from one generator (noise()) and assign them successively

while(simulating)
    x = x + noise()
    y = y + noise()

then the variables x and y become correlated, because the algorithms of the pseudo number generators only make statements about how good they are, if you take every single number generated and not only every second one like in this example. Here, the Brownian particles could maybe move into the positive x and y directions with a higher probability than in the negative directions and thus introduce an artificial drift.

For two further reasons to use different generators look at sehe's answer.

like image 21
LSchueler Avatar answered Oct 01 '22 06:10

LSchueler