Solution Exercise 39

In this exercise you will simulate 1,000 rolls of two dice. Begin by writing a function that simulates rolling a pair of six-sided dice. Your function will not take any parameters. It will return the total that was rolled on two dice as its only result.

Write a main program that uses your function to simulate rolling two six-sided dice 1,000 times. As your program runs, it should count the number of times that each total occurs. Then it should display a table that summarizes this data. Express the frequency for each total as a percentage of the total number of rolls. Your program should also display the percentage expected by probability theory for each total. Sample output is shown below.

Total Simulated % Expected %
2 2.90 2.68
3 6.90 5.56
4 9.40 8.33
5 11.90 11.11
6 14.20 13.89
7 14.20 16.67
8 15.00 13.89
9 10.50 11.11
10 7.90 8.33
11 4.50 5.56
12 2.60 2.78

 

Hint:
To simulate dice rolls first import random to your module. Then you can simulate the roll by using the code

r = random.randrange(6) +1

The reason we use +1 is that randrange will give us a random number from 0 and up to but not including the number we pass to it.

import random
def two_dice_roll():
    dice1 = random.randrange(6) +1
    dice2 = random.randrange(6) +1
    return dice1 + dice2

def main():
    #Create a dictionary for the results and set all values to 0
    result_dict = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
    
    #Simulate 1000 rolls and store the result
    for turn in range(1000):
        result = two_dice_roll()
        #Add one to the dict using result as the key and by increasing its value by one
        result_dict[result] += 1
        
    #Now present the result
    #First the title row.We use the rjust method on the strings to right adjust 
    #the text
    print("Total".rjust(16),"|", "Simulated %".rjust(16),"|", "Expected %".rjust(16))
    print("-------------------------------------------------------")
    #Now print the results
    for n in range(2,13):
        #Calculate the simulated result and format it with 2 decimal
        #places and convert it to a string
        sim_result = str("%.2f"%(result_dict[n]/1000*100))
        #To calculate the expected result we need to consider
        #That the result of 7 is the most probable one 
        if n <= 7:
            exp_result = str("%.2f"%((n-1)/36*100))
        else: #so if n is greater than 7 we need to reduce the probability
            exp_result = str("%.2f"%((12-n+1)/36*100))
        #Now print this row using rjust method
        print(str(n).rjust(16),"|",sim_result.rjust(16),"|",exp_result.rjust(16))

if __name__ == '__main__':
    main()