|
Boost Users : |
Subject: Re: [Boost-users] [random] Singleton engine
From: Kevin Martin (kev82_at_[hidden])
Date: 2009-07-26 06:47:20
On 26 Jul 2009, at 03:44, Diederick C. Niehorster wrote:
> I have been writing a wrapper around the variate_generator as I always
> want to use the same number generator, but do want to use different
> distributions.
I must admit I haven't read all your code in detail, so it may do more
than I realise, but I had the same problem as this a while ago. My
solution was a little simpler, I just use a static boost::shared_ptr
to hold the singleton instance and for a given distribution I put the
variate_generator into a boost::function.
I like this approach because it will cause an exception if I try and
use the generator before I've seeded it, and it will also complain if
I accidently initialise it more than once.
Thanks,
Kevin Martin
static boost::shared_ptr<boost::mt19937> generator_;
boost::mt19937 &grng_generator() {
if(generator_) return *generator_;
throw std::runtime_error("Requrested RNG, but there isn't one");
}
void grng_setGenerator(boost::shared_ptr<boost::mt19937> ptr) {
if(!ptr) throw std::runtime_error("Tried to set generator to NULL
pointer");
if(generator_) throw std::runtime_error("Tried to set generator
more than once");
generator_ = ptr;
}
template<class Distribution_>
boost::function0<typename Distribution_::result_type>
grng_randomVariable(const Distribution_ &d) {
boost::variate_generator<boost::mt19937&, Distribution_> rv(
grng_generator(), d);
return boost::function0<typename Distribution_::result_type>(rv);
}
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