In [1]:
import random
from scipy.stats import chi2, poisson
In [2]:
# roll 36 4-sided dice
rolls = [random.randint(1, 4) for i in range(36)]
print(rolls)
[2, 3, 4, 1, 3, 2, 1, 2, 2, 1, 3, 1, 3, 1, 2, 3, 2, 4, 2, 1, 4, 3, 4, 4, 3, 4, 1, 3, 4, 4, 3, 1, 4, 2, 1, 4]
In [3]:
expected = [9, 9, 9, 9]
# count each of the 1s, 2s, 3s, and 4s
observed = [rolls.count(1), rolls.count(2), 
            rolls.count(3), rolls.count(4)]
print(expected)
print(observed)
# [9, 9, 9, 9]
# [9, 8, 9, 10]
# by hand -> 2/9 chi2
[9, 9, 9, 9]
[9, 8, 9, 10]
In [4]:
# calculate the chi^2-value
chi_squared = ((rolls.count(1) - 9) ** 2 / 9) + \
                ((rolls.count(2) - 9) ** 2 / 9) + \
                ((rolls.count(3) - 9) ** 2 / 9) + \
                ((rolls.count(4) - 9) ** 2 / 9)
print(chi_squared)
0.2222222222222222
In [5]:
# get our p-value
degrees_of_freedom = 3 # 4 - 1
print(1 - chi2.cdf(chi_squared, df = degrees_of_freedom))
0.9739245692310424