Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • 1
    It is <cstdlib> in C++ Commented May 5, 2011 at 1:50
  • 7
    This mistakes keeps getting repeated again and again and again. The problem is that it feed of itself and is just so common around the web it is hard to iradicate. This is the standard anti-pattern for generating a random number in a range. There are two problems. 1) The bottom bits from rand() are less random than the top bits (% basically uses the bottom bits). 2) Unless the divisor (3 in this case) is an exact factor of RAND_MAX the last few values are slightly less probable than the other values (thus skewing your probability). Commented May 5, 2011 at 7:00
  • A better solution is: randNum = (rand() * 1.0 / RAND_MAX * 3) + 1 Commented May 5, 2011 at 7:02
  • 2
    @Martin: you can't state as a fact that bottom bits are less random. That used to be a problem in the eighties. And your "better alternative" doesn't solve the skewed probability. If you need bullet-proof random-number generation, use the Boost stuff, or C++11. For beginners, this is sufficient. Commented May 5, 2011 at 7:17
  • 2
    Absolutely a better solution is to use Boost random number generator it was written by people who actually understand the problems associated with random numbers. Actually the solution I present (not mine) does solve the skew problem (notice it uses real numbers not integers). Also yes the bad random distribution of the bottom bits is an old problem that has been made better. But unless you know what rand is doing you can't tell if it has been solved in your variant of rand(). Thus it is more portable to air on the side of safety and write code that will work everywhere. Commented May 5, 2011 at 7:52