random library: initializaing a generator.

Hi
I am using boost/random library in order to create a normal distributed
noise.
I want to call my my_class::noise() functions several times, but I want to
initialize the generator only once.
I tried to declare and initialize the generator at the constructor of
my_class, but then my_class::noise() doesn't recognized the generator.
I wrote it the following way:
my_class::my_class()
{
boost::mt19937 gen(42u);
}
my_class::noise()
{
boost::normal_distribution<float> n_d(5, 10); //n_d(mean,stdev)
boost::variate_generator
normal(gen, n_d);
return normal(); } I guess I need to declare the generator at the header, and only initialize it at the constructor, but I don't know how to do it. Thanks for your help. Dvir

You could use static local variables, but that's not threadsafe. On the other hand, Since a constant value is written, it doesn't need to be a problem, even in a multi threaded environment. example: int generate() { static int number = 10; return number++; } The above function will return the next number from 10 onward. The initialization of number will only occur at the first call, due to the variable being static. Maybe this is a solution you can use, agb

dvir schirman wrote:
If you just want the generator to be initialized once for each object of
my_class that is created, this will do the trick:
class my_class
{
protected:
typedef boost::mt19937 generator_type;
typedef boost::normal_distribution<> normal_distribution_type;
typedef boost::variate_generator
participants (4)
-
Anne-Gert Bultena
-
Carlo Wood
-
David Walthall
-
dvir schirman