Say you have a random bit generator, a flipped coin, for instance, which has a 0.5 chance of generating a 0, and a 0.5 chance of generating a 1. Now say you’re not satisfied with bits; you want to generate a single random integer from the set {0, 1, 2} such that any of the three possibilites has an equal chance of being generated. One way of doing this is to generate two random bits, and to act accordingly:
Two bits - result
00 - generate 0
01 - generate 1
10 - generate 2
11 - repeat
Do you see how that works? If you get a 11, you generate two more bits until you get a combination that isn’t 11, and go with that. Now then, for lack of a better term, let’s call this means of generating a random ternary digit Method Alpha. One problem with Method Alpha is that it’s possible that you’ll be generating bits for quite some time (IE you keep getting 1’s from your bit generator). However, that isn’t very likely. I went and did out the math for this, and if I did it right, the expected (average) value for the number of bits you’ll have to generate is 8/3. I’ll consider a Method more efficient than another Method if the expected value of the number of bits generated is less.
Question the First: Is there any Method of generating a single random ternary digit which is more efficient than Method Alpha?
Question the Second: Is there any Method of generating a single random ternary digit for which the possible number of bits generated has an upper limit?
Now, I’m betting the answers to those two questions are No and No, so I decided to make this more interesting. You can use Method Alpha to generate a random digit of base N, but you may have to generate more than two random bits at a time. For instance, for base 5, use the following table:
000 - generate 0
001 - generate 1
010 - generate 2
011 - generate 3
100 - generate 4
101 - repeat
110 - repeat
111 - repeat
The number of bits you have to generate at a time, k, is ceil(log[sub]2[/sub]N), where ceil represents the least-integer-greater-than-or-equal-to function. Empirically, I have found that the expected value of Method Alpha, for any given N, is k×2[sup]k[/sup]/N, where k is defined as above.
Question the Third: Is there any Method of generating a single random base N digit, where N is any prime number, that is more efficient than Method Alpha?
Thanks in advance for your many enlightening posts.