BDE 4.14.0 Production release
|
Provide a class to generate random numbers using the PCG algorithm.
This component provides a single mechanism class, bdlb::PcgRandomGenerator
, that is used to generate random numbers employing the PCG algorithm, a high-performance, high-quality RNG. PCG stands for "permuted congruential generator" (see http://www.pcg-random.org for details). The PCG technique employs the concepts of permutation functions on tuples and a base linear congruential generator. The PCG algorithm is seeded with two values: its initial state and a "stream
selector." The stream selector is intended to address a potential hazard of multiple instances of a random number generator having unintended correlation between their outputs. For example, if we allow them to have the same internal state (e.g., mistakenly seeding them with the current time in seconds), they will output the exact same sequence of numbers. Employing a stream selector enables the same initial state to generate unique sequences. Free operators ==
and !=
provide the operational definition of value. Refer to O'Neill (2014) at https://www.pcg-random.org/pdf/hmc-cs-2014-0905.pdf for details.
This section illustrates intended use of this component.
This example shows how one might use bdlb::PcgRandomGenerator
to create and use a class to simulate the roll of a single die in a game, such as craps, that uses dice.
First, we define the Die
class itself:
Now, we can use our Die
class to get the random numbers needed to simulate a game of craps. Note that the game of craps requires two dice.
We can instantiate a single Die
and role it twice:
Alternatively, we could create two instances of Die
, with separate initial states/sequences, and role each one once:
Note that the specification of separate seeds is important to produce a proper distribution for our game. If we had shared the seed value each die would always produce the same sequence of values as the other.
This example illustrates how a stream selector can be used to guarantee that two distinct instances of PcgRandomGenerator
produce uncorrelated sequences.
First, we use bdlb::RandomDevice
to choose the initial states for the generators using a source of true randomness:
Then we select two distinct stream selectors for the generators, which, due to the PCG algorithmic properties, will guarantee that the sequences will be uncorrelated even if the initial state is exactly the same:
Finally, we initialize the generators with their respective initial states and stream selectors and check that they produce distinct sequences of random numbers. The check is guaranteed to pass even in the rare, but possible case of state1 == state2
: