Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tutorial or example code for extending c++11 random with generators and distributions

I have legacy C++ code that I wrote to generate uniform random numbers and a Gaussian distribution. It implements algorithms by Dr. George Marsaglia that are extremely fast. (I was using them to generate skazillions of samples for Monte Carlo high-dimensional integration.)

I think it would be a good idea to re-factor the generator and distribution to work with the new C++11 std::random scheme.

Can anyone point me to a tutorial or a good reference for std::random that includes the necessary info for how to extend it? Example code would be ideal.

UPDATE. Thanks for everyone's help. I have now written a drop-in replacement for the std::normal_distribution that ships with Visual C++ 2010. On my machine, the replacement is 26% faster when fed by the default engine. I am a little disappointed that the difference is not bigger, but hey, that's my problem. :-)

like image 838
Jive Dadson Avatar asked Jul 30 '12 07:07

Jive Dadson


2 Answers

N3376 is the latest draft C++ standard (this is post C++11, but is an excellent snapshot of C++11).

Everything C++11-random is in: 26.5 Random number generation [rand]

26.5.1.4 Random number engine requirements [rand.req.eng] has all of the requirements your uniform random number generator would need to fulfill.

26.5.1.6 Random number distribution requirements [rand.req.dist] has all of the requirements your Gaussian distribution would need to fulfill.

26.5.8.5.1 Class template normal_distribution [rand.dist.norm.normal] is the section describing the std-defined Gaussian distribution.

The C++11 <random> is very STL-like in that it sets up requirements for random number generators (containers), and random distributions (algorithms), and then the client can mix and match the two. It's a really very cool design.

Sorry, I don't know of a good tutorial. The C++ standard is an excellent reference and a lousy tutorial. However you are obviously well educated in the domain of random numbers. So assuming you know a thing or two about C++, the C++ standard may not be too bad.

Open source implementations of <random> are available if you want to peruse their source (for an example). One example is libc++. All they ask is that you retain their copyright notices if you reuse any of their code.

Edit

You are uniquely qualified to write this tutorial. :-)

like image 147
Howard Hinnant Avatar answered Oct 31 '22 11:10

Howard Hinnant


You can learn a lot by reading boost library sources, since many proposals in C++11 were adopted from boost.

Take a look at the interface of an example rng engine here:

http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine

I would start by implementing the min max seed and operator() functionalities to see if it passes as a valid engine for C++11

like image 23
nurettin Avatar answered Oct 31 '22 11:10

nurettin