Generating random numbers – C++

Okay, so I was given a task of codifying the genetic algorithm. As genetic algorithm depends a lot on the random numbers, I started searching the internetz for a good method for generating random numbers. Of course, the first hit was the rand() function – the good ole’ tried and tested method. So we have something like this

 #define RANGE 10000

 ...

 srand(time(0));
 int var = rand() % RANGE;

Obviously, using the ‘%’ with the rand() has its own problems, and often more than not, gives a not-so-random distribution. This led me to further searching and I stumbled across Boost.Random .

#include <boost/random/uniform_int.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/mersenne_twister.hpp>
int main() {
  boost::mt19937 gen;
  boost::uniform_int<> int_dist(1,10);  // generate integers from [1,9)
  std::cout << int_dist(gen);

  boost::uniform_real<> real_dist(1.0,10.0);
  std::cout << real_dist(gen);
  return 0;
}

The mt19937 is based on Mersenne Twister – a random number generator. It can be used along with many a distribution, like Bernoulli’s, Binomial, Uniform – to name a few. The above example makes use of the uniform integer distribution, and uniform real number distribution to generate an integer and a real number respectively.

With c++0x, these are already a part of the standard library, so if you are using a newer compiler – then you’re in luck.

#include <iostream>
#include <random>
int main() {
  std::mt19937 gen;
  std::uniform_int_distribution int_dist(0, 19);
  std::cout << int_dist(gen);

  std::uniform_real_distribution real_dist(1.0,10.0);
  std::cout << real_dist(gen);
  return 0;
}

This compiles happily with g++ 4.6.1 with -std=c++0x option.

So well, I was quite happy the way random numbers were generated, and needless to say, the algorithm works pretty good šŸ™‚

Advertisements
Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s