Declaring normal distribution generator in .h file

I have a member function that I want to generate a lot of random numbers, but I don't want to initialize the random number generator on every call to that function, thinking it would be slower. I was thinking I could declare the random number generator in the .h file and initialize it in the constructor, but I am unsure of the syntax to do this, or even if it will work. Also, I am not sure if this is indeed necessary to save computation time. Any help would be appreciated!
You should only initialize it once for sure.

if you are using the c++ random generators, you can initialize that in main once.
If you are using your own or a class wrapper around it or something, you can initialize it in your class.

If it is your own class, you can make the "seeds" static so all copies of the class are pulling from the same stream, which would make local copies of the class as efficient as passing it around as a parameter, if you coded it with that mindset from the start. The first one would initialize it.

Is computation time a real concern?
> I was thinking I could declare the random number generator in the .h file and initialize it in the constructor

Yes.

Something along these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <random>

struct my_class
{
    my_class() = default ; // uses the default member initialise 

    my_class( std::size_t seed, double mean, double std_dev ) : rng(seed), distrib(mean,std_dev) {}

    void change_param( double mean, double std_dev ) // modify mean and standard deviation
    { distrib.param( decltype(distrib)::param_type{ mean, std_dev } ) ; }

    double generate() { return distrib(rng) ; }

    private:

        // default member initializer seeds the rng with a random value
        // 32 bits of randomness would be adequate for most programs
        std::mt19937 rng { std::random_device{} () } ;

        // default constructor initialises distrib to a standard normal distribution (mean 0, stddev 1)
        std::normal_distribution<double> distrib ;
};

int main()
{
     my_class mc ;
     for( int i = 0 ; i < 5 ; ++i ) std::cout << mc.generate() << ' ' ;
     std::cout << '\n' ;

     mc.change_param( 20.0, 7.5 ) ;
     for( int i = 0 ; i < 5 ; ++i ) std::cout << mc.generate() << ' ' ;
     std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/c3dbd1a5fce6e68d
Topic archived. No new replies allowed.