|
Boost Users : |
From: David Walthall (walthall_at_[hidden])
Date: 2006-06-06 10:37:57
dvir schirman wrote:
> 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.
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<generator_type &,
normal_distribution_type> normal_random_type;
generator_type m_generator;
normal_distribution_type m_normal_distribution;
normal_random_type m_normal_random;
public:
my_class() :
m_generator(42u), m_normal_distribution(5,10),
m_normal_random(m_generator, m_normal_distribution)
{
; // do nothing
}
double noise()
{
return m_normal_random();
}
};
If you want the generator to be initialized only once total (no matter
how many instances of the class are created), you can use this:
class my_class_static
{
protected:
typedef boost::mt19937 generator_type;
typedef boost::normal_distribution<> normal_distribution_type;
typedef boost::variate_generator<generator_type &,
normal_distribution_type> normal_random_type;
static generator_type m_generator;
static normal_distribution_type m_normal_distribution;
static normal_random_type m_normal_random;
public:
static double noise()
{
return m_normal_random();
}
};
You never actually need an instance of the class my_class_static since
the noise function is static. The static member m_generator will be
initialized only once, at program startup. (Note that this is not
thread-safe and would need to be protected with a lock.)
David
Testing code:
static void Test_my_class()
{
my_class mine;
for(unsigned int i=0 ; i<9 ; ++i)
{
double d = mine.noise();
std::cout << d << " ";
}
std::cout << std::endl;
}
static void Test_my_class_static()
{
for(unsigned int i=0 ; i<9 ; ++i)
{
double d = my_class_static::noise();
std::cout << d << " ";
}
std::cout << std::endl;
}
int main(int argc, char* argv[])
{
std::cout << "Testing my_class - next two lines should be same\n";
Test_my_class();
Test_my_class();
std::cout << "Testing my_class_static - next line same as above,
last line different\n";
Test_my_class_static();
Test_my_class_static();
return 0;
}
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net