How would I seed the PCG RNG with a chosen, set seed?

Viewed 130

For testing purposes I need to seed PCG's C++ implementation (the 64 bit output one) with a set value. When I look at the examples I only see it seeding using entropy.

I've used

pcg64 rng(42);

and it's worked, rng() generating the same numbers every time, but PCG64 uses a 256-bit seed and this way seems to generate the same numbers for each value above the 64 bit integer limit.

What's the best way to seed it with known values?

1 Answers

As I read source code, pcg64 is an instantination of engine template class which accepts pcg128_t seed value in constructor. So it is only 128 bit value, not 256 bit.

There are two ways how you can pass 128 bit seed to constructor. First is if you already have pre-defined two 64-bit values, then you can use PCG_128BIT_CONSTANT(hi, lo) macro for building 128 bit value, and write code:

pcg64 rng{PCG_128BIT_CONSTANT(0xC7C8709C9626D159ULL, 0x675BB824D76E9146ULL)};

Second way is by using std::mt19937_64 random generator and maybe std::random_device (for initializing random generator):

#include <random>
....
std::mt19937_64 seed{0xC7C8709C9626D159ULL};
// or
// std::mt19937_64 seed{std::random_device()};
pcg64 rng{PCG_128BIT_CONSTANT(seed(), seed())};

You can also use std::seed_seq for same purpose as std::mt19937_64 was used above:

#include <random>
#include <array>
#include <cstdint>
....
std::seed_seq seed{1, 2, 3, 4, 5};
std::array<uint32_t, 4> seeds{};
seed.generate(seeds.begin(), seeds.end());
pcg64 rng{PCG_128BIT_CONSTANT(((uint64_t(seeds[0]) << 32) | seeds[1]),
    ((uint64_t(seeds[2]) << 32) | seeds[3]))};
Related