I'm trying to precompute random values using C++11's random
library at compile time. I'm mostly following examples. What am I doing wrong here?
using namespace std; #include <iostream> #include <vector> #include <random> vector<double> rands; typedef std::mt19937_64 RNG; uint64_t seed_val; RNG rng; void initialize() { rng.seed(seed_val); } constexpr vector<double> generate_random( ) //size_t numbers) { int numbers = 1000; std::uniform_real_distribution<double> zero_one(0.0, 1.0); for (unsigned int i = 0; i < numbers; i++) { double rand_num = zero_one(rng); rands.push_back( rand_num ); } return rands; } int main() { cout << "TMP rands"; for_each( rands.begin(), rands.end(), [] (double value) { cout<<value<<endl; }); }
Here's an example compile-time random number generator shamelessly stolen from here, but thought it might be useful for anyone who looks this up:
template<u32 S, u32 A = 16807UL, u32 C = 0UL, u32 M = (1UL<<31)-1> struct LinearGenerator { static const u32 state = ((u64)S * A + C) % M; static const u32 value = state; typedef LinearGenerator<state> next; struct Split { // Leapfrog typedef LinearGenerator< state, A*A, 0, M> Gen1; typedef LinearGenerator<next::state, A*A, 0, M> Gen2; }; };
Description. The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.
Only constexpr
functions and constant expressions may be evaluated at compile time. That rules out <chrono>
and <random>
.
What you can do is access the __TIME__
preprocessor macro and define your own PRNG composed of one-line, constexpr
functions.
There is a research paper on the topic: Random number generator for C++ template metaprograms containing code snippet for the __TIME__
trick. It also talks about supporting different random number engines and distributions as orthogonal choices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With