Created
May 27, 2015 21:34
-
-
Save ttback/cf95cd9236aa702999a3 to your computer and use it in GitHub Desktop.
random bit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment