📅 2010-Nov-24 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, random ⬩ 📚 Archive
Note: Please note that the random header has undergone substantial change for C++11 and later. This post is outdated and only meant for older versions of C++. For the latest, please refer to this page.
C++ can get very irritating if all you want is a simple solution. Take random number generation for example. The
The
Engine: It generates random numbers based on a certain algorithm. There are many engines defined in
Predefined Engine: It is an engine created with some good-quality initial values. This saves a lot of the pain of coming up with values to initialize the engine. There are many predefined engines in
Distribution: It takes the output of an engine and shapes it to fit a certain distribution. An example is uniform_real_distribution, which creates an uniform distribution of real numbers. A distribution needs an engine to provide it with random number input.
Variate Generator: variate_generator is a wrapper to combine an engine (or predefined engine) with a distribution, to create a custom random number generator.
Simple Random Number Generation
Here is a simple random number generator that produces random float values. It uses the variate_generator to wrap a minstd_rand engine and uniform_real_distribution.
#include <random>
using namespace std;
typedef minstd_rand Engine;
typedef uniform_real_distribution<float> Distribution;
typedef variate_generator<Engine, Distribution> Generator;
9999), Distribution( 10, 100 ) );
Generator gen( Engine(
"Random value: " << gen() << endl; cout <<
The minstd_rand engine requires a seed, here we seed it with 9999. We also provide the uniform_real_distribution an output range of [10.0,100.0).
Simple Random Generator Class
If all I want is to generate some random number simply and quickly, the C++
Here is a simple random number generator class that wraps up the complexity to provide a simple interface:
#include <random>
using namespace std;
class MyRandom
{private:
// Types
typedef minstd_rand Engine;
typedef uniform_real_distribution<float> Distribution;
typedef variate_generator<Engine, Distribution> Generator;
// To hold the generator
Generator* _gen;
public:
int seed, float minVal, float maxVal )
MyRandom(
{new Generator( Engine( seed ), Distribution( minVal, maxVal ) );
_gen =
}
~MyRandom()
{delete _gen;
}
float next()
{return (*_gen)();
} };
The above class interface is influenced by C# Random, which is how simple and accessible C++ should have been! Writing code using the above class is easy:
const int seed = 9999;
const float minVal = 10;
const float maxVal = 100;
MyRandom myRand( seed, minVal, maxVal );"Random value: " << myRand.next() << endl; cout <<
I hope this post made digesting