How to generate a random integer number from within a range

后端 未结 11 1232
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 23:57

This is a follow on from a previously posted question:

How to generate a random number in C?

I wish to be able to generate a random number from within a part

11条回答
  •  别跟我提以往
    2020-11-22 00:40

    For those who understand the bias problem but can't stand the unpredictable run-time of rejection-based methods, this series produces a progressively less biased random integer in the [0, n-1] interval:

    r = n / 2;
    r = (rand() * n + r) / (RAND_MAX + 1);
    r = (rand() * n + r) / (RAND_MAX + 1);
    r = (rand() * n + r) / (RAND_MAX + 1);
    ...
    

    It does so by synthesising a high-precision fixed-point random number of i * log_2(RAND_MAX + 1) bits (where i is the number of iterations) and performing a long multiplication by n.

    When the number of bits is sufficiently large compared to n, the bias becomes immeasurably small.

    It does not matter if RAND_MAX + 1 is less than n (as in this question), or if it is not a power of two, but care must be taken to avoid integer overflow if RAND_MAX * n is large.

提交回复
热议问题