How do I scale down numbers from rand()?

后端 未结 9 1939
小蘑菇
小蘑菇 2020-11-27 14:38

The following code outputs a random number each second:

int main ()
{
    srand(time(NULL)); // Seeds number generator with execution time.

    while (true)         


        
9条回答
  •  醉梦人生
    2020-11-27 15:06

    All the examples posted so far actually give badly distributed results. Execute the code often and create a statistic to see how the values become skewed.

    A better way to generate a real uniform random number distribution in any range [0, N] is the following (assuming that rand actually follows a uniform distribution, which is far from obvious):

    unsigned result;
    do {
        result = rand();
    } while (result > N);
    

    Of course, that method is slow but it does produce a good distribution. A slightly smarter way of doing this is to find the largest multiple of N that is smaller than RAND_MAX and using that as the upper bound. After that, one can safely take the result % (N + 1).

    For an explanation why the naive modulus method is bad and why the above is better, refer to Julienne’s excellent article on using rand.

提交回复
热议问题