Generate random numbers uniformly over an entire range

后端 未结 17 2653
野性不改
野性不改 2020-11-22 04:21

I need to generate random numbers within a specified interval, [max;min].

Also, the random numbers should be uniformly distributed over the interval, not located to

17条回答
  •  眼角桃花
    2020-11-22 05:18

    The solution given by man 3 rand for a number between 1 and 10 inclusive is:

    j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
    

    In your case, it would be:

    j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));
    

    Of course, this is not perfect randomness or uniformity as some other messages are pointing out, but this is enough for most cases.

提交回复
热议问题