How to make dice (uniform) distribution using coin toss?

Viewed 167

I can use only randint(0,1), it's tossing coin (50% head, tail).

Using above, how can I make dice distribution (1 to 6 uniform distribution)?

I just think that if I toss many times enough, and sum all results, then %6, it will be uniform dice distribution, but is there a smarter method (it takes long for above)?

2 Answers

You can do the following (implemented in Python):

from random import randint

def toss():
    while True:
        t =sum([2**i * randint(0,1) for i in range(3)])
        if t < 7 and t > 0:
           return t
       
        
rolls = [0] * 7
N = 1000000
for i in range(N):
    t = toss()
    rolls[t] += 1
    
print(rolls[1:])

Adding up random numbers makes them more nearly Gaussian, which isn't uniform, so that won't work.

How about using 0/1 values to set bits in an integer? That works just right to get a number on the range 0 to 2māˆ’1 where m is the number of bits.

To get other ranges, try rejection sampling – first generate 0 to 2m, then just try again if the number is outside the range you want.


This was originally a comment by Robert Dodier.

Related