Why do people say there is modulo bias when using a random number generator?

前端 未结 10 1219
一整个雨季
一整个雨季 2020-11-21 05:48

I have seen this question asked a lot but never seen a true concrete answer to it. So I am going to post one here which will hopefully help people understand why exactly the

10条回答
  •  粉色の甜心
    2020-11-21 06:33

    Keep selecting a random is a good way to remove the bias.

    Update

    We could make the code fast if we search for an x in range divisible by n.

    // Assumptions
    // rand() in [0, RAND_MAX]
    // n in (0, RAND_MAX]
    
    int x; 
    
    // Keep searching for an x in a range divisible by n 
    do {
        x = rand();
    } while (x >= RAND_MAX - (RAND_MAX % n)) 
    
    x %= n;
    

    The above loop should be very fast, say 1 iteration on average.

提交回复
热议问题