HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMajor

How to simulate a die given a fair coin

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
coinfairsimulatediehowgiven

Problem

Suppose that you're given a fair coin and you would like to simulate the probability distribution of repeatedly flipping a fair (six-sided) die. My initial idea is that we need to choose appropriate integers $k,m$, such that $2^k = 6m$. So after flipping the coin $k$ times, we map the number encoded by the k-length bitstring to outputs of the die by dividing the range $[0,2^k-1]$ into 6 intervals each of length $m$. However, this is not possible, since $2^k$ has two as its only prime factor but the prime factors of $6m$ include three. There should be some other simple way of doing this, right?

Solution

What you can do, is to employ a method called rejection sampling:

  • Flip the coin 3 times and interpret each flip as a bit (0 or 1).



  • Concatenate the 3 bits, giving a binary number in $[0,7]$.



  • If the number is in $[1,6]$, take it as a die roll.



  • Otherwise, i.e. if the result is $0$ or $7$, repeat the flips.



Since $\frac 68$ of the possible outcomes lead to termination in each set, the probability of needing more than $l$ sets of flips to get a die roll is $(1-\frac 68)^l = \dfrac 1{4^l}$. Hence, this method is efficient in practice.

Improvements:

@Angel's answer points out, that the number of coin flips in each set but the first can be reduced from 3 to 2, by using the distinction between a $0$ and a $7$ as the first bit for the next set.

@Emanuele Paolini explains, how you can reduce the number of rerolls, if you need multiple die rolls.

Context

StackExchange Computer Science Q#29204, answer score: 29

Revisions (0)

No revisions yet.