Skip to content

Instantly share code, notes, and snippets.

@akleemans
Created January 13, 2018 23:06
Show Gist options
  • Save akleemans/ca883e72a1f552353607c759449e9ff4 to your computer and use it in GitHub Desktop.
Save akleemans/ca883e72a1f552353607c759449e9ff4 to your computer and use it in GitHub Desktop.
Simulate throwing a dice and waiting until all numbers appear
''' Simple script for throwing a dice over and over until all numbers appeared at least once. '''
from __future__ import division
import random
import time
n = 10**5
r = random.SystemRandom()
def number_of_dice_throws():
count = 0
throws = [False, False, False, False, False, False]
while not throws[0] or not throws[1] or not throws[2] or not throws[3] or not throws[4] or not throws[5]:
throws[r.randint(0, 5)] = True
count += 1
return count
def get_percentile(f, p):
val = 5
total_sum = 0.0
while total_sum < p and val < max(f):
val += 1
if val in f: total_sum += f[val]
else: total_sum += 0.0
return val
# try n times
results = []
i = 0
start = time.time()
while i < n:
results.append(number_of_dice_throws())
i += 1
# aggregate all results
aggregated = {}
for result in results:
if result in aggregated: aggregated[result] += 1
else: aggregated[result] = 1
# calculate experimental pdf
f = {}
for k in aggregated:
prob = aggregated[k]/n
f[k] = prob
print [str(v) + ': ' + str(f[v]*100) for v in f]
print '\n==================\nPercentiles:'
print '50%:', get_percentile(f, 0.5), 'throws'
print '90%:', get_percentile(f, 0.9), 'throws'
print '95%:', get_percentile(f, 0.95), 'throws'
print '99%:', get_percentile(f, 0.99), 'throws'
print 'Finished in', round(time.time()-start, 2), 's'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment