Million Dice Statistics

Tags: tiny, beginner, math, simulation

When you roll two six-sided dice, there’s a 17 percent chance you’ll roll a 7. That’s much better than the odds of rolling a 2: just 3 percent. That’s because there’s only one combination of dice rolls that gives you 2 (the one that occurs when both dice roll a 1), but many combinations add up to seven: 1 and 6, 2 and 5, 3 and 4, and so on.

But what about when you roll three dice? Or four? Or 1,000? You could mathematically calculate the theoretical probabilities, or you can have the computer roll a number of dice one million times to empirically figure them out. This program takes that latter approach. In this program, you tell the computer to roll N dice one million times and remember the results. It then displays the percentage chance of each sum.

This program does a massive amount of computation, but the computation itself isn’t hard to understand.

million_dice_statistics.py
 1"""Million Dice Roll Statistics Simulator
 2By Al Sweigart al@inventwithpython.com
 3A simulation of one million dice rolls.
 4This code is available at https://nostarch.com/big-book-small-python-programming
 5Tags: tiny, beginner, math, simulation"""
 6
 7import random, time
 8
 9print('''Million Dice Roll Statistics Simulator
10By Al Sweigart al@inventwithpython.com
11
12Enter how many six-sided dice you want to roll:''')
13numberOfDice = int(input('> '))
14
15# Set up a dictionary to store the results of each dice roll:
16results = {}
17for i in range(numberOfDice, (numberOfDice * 6) + 1):
18    results[i] = 0
19
20# Simulate dice rolls:
21print('Simulating 1,000,000 rolls of {} dice...'.format(numberOfDice))
22lastPrintTime = time.time()
23for i in range(1000000):
24    if time.time() > lastPrintTime + 1:
25        print('{}% done...'.format(round(i / 10000, 1)))
26        lastPrintTime = time.time()
27
28    total = 0
29    for j in range(numberOfDice):
30        total = total + random.randint(1, 6)
31    results[total] = results[total] + 1
32
33# Display results:
34print('TOTAL - ROLLS - PERCENTAGE')
35for i in range(numberOfDice, (numberOfDice * 6) + 1):
36    roll = results[i]
37    percentage = round(results[i] / 10000, 1)
38    print('  {} - {} rolls - {}%'.format(i, roll, percentage))

https://inventwithpython.com/bigbookpython/project46.html