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

前端 未结 10 1364
一整个雨季
一整个雨季 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:36

    I just wrote a code for Von Neumann's Unbiased Coin Flip Method, that should theoretically eliminate any bias in the random number generation process. More info can be found at (http://en.wikipedia.org/wiki/Fair_coin)

    int unbiased_random_bit() {    
        int x1, x2, prev;
        prev = 2;
        x1 = rand() % 2;
        x2 = rand() % 2;
    
        for (;; x1 = rand() % 2, x2 = rand() % 2)
        {
            if (x1 ^ x2)      // 01 -> 1, or 10 -> 0.
            {
                return x2;        
            }
            else if (x1 & x2)
            {
                if (!prev)    // 0011
                    return 1;
                else
                    prev = 1; // 1111 -> continue, bias unresolved
            }
            else
            {
                if (prev == 1)// 1100
                    return 0;
                else          // 0000 -> continue, bias unresolved
                    prev = 0;
            }
        }
    }
    

提交回复
热议问题