mercredi 16 janvier 2019

How to write a function to create and return a random engine in c++

I have been struggling with C++ pseudo-random-number generation. I would like to write a method createRandEngine to render a random engine. Then some other method (per say gaussian) uses this engine to generate random numbers. I've tried the following code, but I got two compile-time errors from the line **.

#include <random>

typedef std::default_random_engine rand_engine;
rand_engine createRandEngine(const int &seed)
{
    std::seed_seq _s (unsigned(seed));
    rand_engine _eng(_s);  //**

    return _eng;    // Check if we can find alternative ways to render _eng
}


double gaussian(rand_engine &eng, const double &u, const double &std_dev)
{
    std::normal_distribution<double> _g(u, std_dev);
    double _val = _g(eng);
    return _val;
}


int main ()
{
    rand_engine eng = createRandEngine(20190117);
    double norm     = gaussian(eng, 0., 1.);

    std::cout << std::to_string(norm);
}


The two errors state:

error: no matching function for call to ‘std::linear_congruential_engine<long unsigned int, 16807ul, 0ul, 2147483647ul>::seed(std::seed_seq (&)(unsigned int))’


error: no type named ‘type’ in ‘struct std::enable_if<false, void>’ linear_congruential_engine<_UIntType, __a, __c, __m>::

I am relatively new to C++. Any help with my code or showing your ways to do it will be deeply appreciated.




Aucun commentaire:

Enregistrer un commentaire