A function that generates a different number at each call: should I pass the engine, the distribution or both?

StackOverflow https://stackoverflow.com/questions/22252209

Frage

I have some difficulties to understand exactly the role of the distribution regarding a given random engine. Suppose I want to write a function f(/* Arguments */) that returns a new random number at each call using a std::mt19937 engine and a std::uniform_int_distribution<int>. I want this function to be thread safe. My question is the following: should I pass by reference to this function, the engine, the distribution or both ?

War es hilfreich?

Lösung

It's possible for distributions to cache some state and thereby reduce the frequency of calls to the engine to obtain entropy. For example, the Box-Muller transform maps two samples from a uniform distribution into two samples from a normal distribution. It's possible to implement std::normal_distribution via Box-Muller so that it makes two calls to the engine for every second call to the distribution.

Ideally you would store an engine and distribution per-thread - or more granular, but certainly not less - and pass a lambda or std::function<int()> to your function f to insulate it from the details of how the random numbers are obtained.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top