Skip to content

Instantly share code, notes, and snippets.

@map0logo
Created February 1, 2021 21:26
Show Gist options
  • Save map0logo/1a5e3d33844a86e22f5ad14a630dba59 to your computer and use it in GitHub Desktop.
Save map0logo/1a5e3d33844a86e22f5ad14a630dba59 to your computer and use it in GitHub Desktop.
dice_simulation, pandas version
"""Simulating the sum of two dice.
Created on Fri Jan 22 19:02:16 2021
@author: spyderlieber
"""
from random import randrange
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def sim_dice(faces=6):
"""
Roll and sum two dice of a given number of faces.
Parameters
----------
faces : int, optional
Dice number of faces. The default is 6.
Returns
-------
int
Sum of two simulated dice.
"""
d1 = randrange(1, faces + 1)
d2 = randrange(1, faces + 1)
return d1 + d2
def init_count(faces=6):
"""
Initialize expected probabilities and the event counter.
Parameters
----------
faces : TYPE, optional
DESCRIPTION. The default is 6.
Returns
-------
expected : dict
Expected probabilities for each possible outcome.
counts : dict
Counter initialized at zero for each possible outcome.
"""
expected = {
i: (faces - abs(faces - (i - 1))) / faces ** 2
for i in range(2, (faces * 2) + 1)
}
counts = {i: 0 for i in range(2, (faces * 2) + 1)}
return expected, counts
RUNS = 10000
FACES = 6
expected, counts = init_count(FACES)
for i in range(RUNS):
outcome = sim_dice(FACES)
counts[outcome] += 1
sim_array = np.array(list(counts.values())) / RUNS * 100
exp_array = np.array(list(expected.values())) * 100
comparison_table = pd.DataFrame.from_dict(
{"expected": exp_array, "simulated": sim_array}
)
comparison_table.index = expected.keys()
comparison_table.index.name = 'outcomes'
print(comparison_table)
comparison_table.plot.bar()
with plt.xkcd():
comparison_table.plot.bar()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment