|
Boost Users : |
From: Angus Leeming (angus.leeming_at_[hidden])
Date: 2005-10-12 19:10:01
Snorre Jakobsen wrote:
> Hello
>
> I'm sorry if this is answered in the documentation, but I didn't find
> it. I want a function which returns a normally distributed number.
>
> #include <boost/random.hpp>
> #include <time.h>
>
> using namespace boost;
>
> double SampleNormal (double mean, double sigma) {
> mt19937 rng; // select random number generator
> rng.seed((unsigned int) time(0)); // seconds since 1970
> // select desired probability distribution
> normal_distribution<double> norm_dist(mean, sigma);
> // bind random number generator to distribution, forming a
> function variate_generator<mt19937&, normal_distribution<double>
> >
> normal_sampler(rng, norm_dist);
> // sample from the distribution
> return normal_sampler();
> }
>
> This (from http://surl.se/tvk) works very well, except if it's invoked
> (with same parameters) more often than once a second. If so, the
> generator gets equal seeds and returns equal values. How can I construct
> my program so the seeding happens only once?
Hi, Snorre.
Funny! I wrote the very piece of code below this evening!
Make your function a functor, so you initialise the random number generator
only once, in the class' construnctor, but can then use it mulitple times.
Regards,
Angus
#include <boost/random.hpp>
#include <time.h>
class SampleNormal {
typedef boost::mt19937 rng_t;
typedef boost::normal_distribution<double> dist_t;
typedef boost::variate_generator<rng_t&, dist_t> generator_t;
rng_t rng_;
dist_t dist_;
generator_t dice_;
public:
SampleNormal(double mean, double sigma)
: rng_(time(0))
, dist_(mean, sigma)
, dice_(rng_, dist_)
{}
double operator()()
{
return dice_();
}
};
#include <iostream>
int main()
{
SampleNormal normal_sampler(3, 0.5);
for (int i = 0; i != 10; ++i)
std::cout << normal_sampler() << '\n';
std::flush(std::cout);
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