Facey McFaceFace - 1 month ago 5

C++ Question

I'm currently using

`1 + (int)(rand() * 999.0 / RAND_MAX)`

How can I fix this?

Note that although the original code gives a range of 0 to 999 inclusive, I actually want a range of 1 to 999 inclusive.

Answer

Your observation that one digit numbers don't occur as often as two and three digit numbers is not surprising.

There are only 9 one digit numbers (not including zero), but there are 90 two-digit ones, and 900 three digit ones. So a uniform random number generator will draw numbers in that frequency.

To generate random numbers in the range [1, 999] such that the probability of their having 1, 2, and 3 digits is equal, use your favourite generator to generate a random number `p`

, say, in the range [0, 1) (see the new random library functions in C++ to do that), and transform it using `std::pow(1000, p);`

.

You should note that the resulting distribution will not be *piecewise-uniform*: that is to say that the probability of drawing a number with a certain number of digits is not the same as the probability of drawing any other number with that number of digits. But it does have a continuous and differentiable cumulative density function which can be important mathematically.

(For the mathematically-inclined, the transformation I'm applying is the *quantile* function of the distribution that the OP needs).

Source (Stackoverflow)

Comments