Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top