This tutorial shows how we can use Numpy to simulate rolling dice from rolling a single die up to summing the results from multiple rolls. We will also see how to handle situations in which one of the sides of the dice is loaded (it has a greater probability of landing on that side comparing to the rest).

Let's get started!

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

Represent a dice

The first thing we will need is to define how many sides our dice will have. We can even go a step further and represent a dice by using a NumPy array and assigning to each side a label which will be equal to the number of that side:

# Define the desired number of sides (try changing this value!)
n_sides = 6

# Represent a dice by using a numpy array
dice = np.array([i for i in range(1, n_sides+1)])

print(dice)
[1 2 3 4 5 6]

Roll the dice

With our dice ready it is time to roll it. For now we will assume that the dice is fair, which means the probability of landing on each side is the same (it follows a uniform distribution). To achieve this behavior we can use the function np.random.choice, which given a NumPy array returns one of the entries in it randomly:

np.random.choice(dice)

This is great but if we wanted to roll the dice 20 times we will need to run the code 20 times and record each result. Now we need a way to simulate several rolls at the same time. For this we can define the number of rolls we desire and use a list comprehension to roll the dice as many times as we like, we can also save every roll in a NumPy array:

# Roll the dice 20 times
n_rolls = 20

# Save the result of each roll
rolls = np.array([np.random.choice(dice) for _ in range(n_rolls)])

print(rolls)
[4 2 4 2 1 5 3 5 4 2 6 6 5 1 1 6 5 2 4 1]

Now we have a convenient way of keeping track of the result of each roll, nice!

Now we would like to know the mean and variance of this process. For this we can use NumPy's functions np.mean and np.var:

# Compute mean of 20 rolls
m = np.mean(rolls)

# Compute variance of 20 rolls
v = np.var(rolls)

print(f"mean of rolls: {m:.2f}\\nvariance of rolls: {v:.2f}")
mean of rolls: 3.45
variance of rolls: 3.15

We can even check the distribution of the rolls by plotting a histogram of the NumPy array that holds the result of each throw. For this we will use the plotting library Seaborn, concretely the sns.histplot function:

n_rolls_hist = sns.histplot(rolls, discrete=True)
n_rolls_hist.set(title=f"Histogram of {n_rolls} rolls")
plt.show()

Untitled