2021年5月1日土曜日

Normal distribution of dice rolls: Python animation

 Since my wife started learning statistics, and I wanted to give her some intuitive understanding of the normal distribution, standard deviation, 95% confidence region etc, I made a small python code which generates an animation of the histogram of dice rolls.

This could help others time ;)

(Distribute under MIT license)



import random
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm

def main():

numTrial = 1000000
numDice = 20
sumResults = []

bin=np.arange(numDice-0.5, numDice*6+1.5, 1)
print(bin)

fig = plt.figure()
iFig = 1
for iTrial in range(numTrial):
sumDice = 0
for iDice in range(numDice):
sumDice += random.randint(1,6)
sumResults.append(sumDice)

if iTrial % 100 == 0:
ax = fig.add_subplot()
ax.set_title(str(numDice)+" dices case")
ax.set_xlabel("Sum of rolls")
ax.set_ylabel("Frequency")
n, bins, patches = plt.hist(sumResults,bins=bin)

loc,scale = norm.fit(sumResults)
plt.plot(bin,sum(n)*norm.pdf(bin,loc,scale),color="y")
txt = "STD:"+str(round(scale,4))
plt.text(5.0,0.01,txt,size=30)

p25 =norm.ppf(0.025 ,loc,scale)
p975=norm.ppf(0.975,loc,scale)
plt.axvline(x=p25, ymin=0.1, ymax=0.9,color="r")
plt.axvline(x=p975, ymin=0.1, ymax=0.9,color="r")
plt.savefig(str('{:05d}'.format(iFig))+".png")
iFig += 1
plt.pause(.001)
fig.clear()

if __name__ == "__main__":
main()

0 件のコメント:

コメントを投稿