Deterministic uniform distribution needed using C ++ 11

I am using the C ++ 11 random library to generate deterministic random values, I need to restrict the output to different ranges and naturally use std::uniform_int_distribution

, but unfortunately the spec gives too much freedom in library implementations and the output is different between X86-64 Linux and X86 Windows 7.

Is there any option other than implementing my own distribution to ensure that the output is deterministic regardless of the library's implementation?

+3


source to share


2 answers


Is there any option other than implementing my own distribution to ensure the output is deterministic regardless of the library implementation?

There is no alternative other than implementing your own distribution to ensure that the output is deterministic regardless of the library implementation. While engines are deterministic, distributions are not.



Typical implementations for uniform_int_distribution

will include "culling" algorithms that will repeatedly get a number from the URNG, and if that result is not in the desired range, throw it away and try again. Variations on this topic will optimize this algorithm by bending the range values ​​into values ​​within the range to minimize variance without shifting the acceptance range, as the simplified algorithm does offset + lcg() % range

.

+2


source


At least if the LCG is good enough for your purpose, std::linear_congruential_engine

created using some of the fixed constants your application provides, it should produce deterministic output.

typedef uint64_t number;
constexpr number a {1};
constexpr number c {2};
constexpr number m {3};
constexpr number seed {0};
std::linear_congruential_engine<number, a, c, m> lcg {seed};
std::uniform_int_distribution<number> dist {0, 1000};
for (int i = 0; i < 10; ++i)
  std::cout << dist(lcg) << std::endl;

      



Note that I deliberately chose stupid values ​​for a

, c

and m

, in order to ignore the debate about making a good set of parameters.

+1


source







All Articles