random data generator for C

Let’s consider whether this random number generator is ‘good’ or not.

random1 = rand() % 2;

There are two problems with this approach. One is that the low order bits of the random number generator are not particularly random, so neither with random1 be. On my machine, there’s a slight but measurable bias toward 0 with that. The second problem is that it’s not thread safe because rand stores hidden state. A better solution, if your compiler and library supports it, would be to use the C++11 `std::uniform_int_distribution. It looks complex, but it’s actually pretty easy to use. One way to do that (from Stroustrup) is like this:

int rand_int(int low, int high)
{
  static std::default_random_engine re {};
  usingDist = std::uniform_int_distribution<int>;
  staticDist uid {};
  return uid(re,Dist::param_type{low,high});
}

This still stores state, but at least the distribution is correct.

Source: http://codereview.stackexchange.com/questions/49614/text-based-adventure-game-with-too-many-conditional-statements

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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