from random import randint
import math
import matplotlib.pyplot as plt
import matplotlib.animation
from IPython.display import HTML
def jeu(mise):
lancer1 = randint(1,8)
if lancer1 == 1:
gain = mise
else:
lancer2 = randint(1,8)
if lancer2 <= 4:
gain = 6
else:
gain = -mise
return gain
def gainMoyen(mise, n):
gainTotal = 0
for i in range(n):
gainTotal = gainTotal + jeu(mise)
return gainTotal/n
def cumul(n):
F = []
gainTotal = 0
for i in range(n):
gainTotal = gainTotal + jeu(mise)
F.append(gainTotal/(i+1))
return F
def esperance(X,P):
E = 0
for i in range(len(X)):
E = E + X[i]*P[i]
return E
def ecartType(X,P):
E = esperance(X,P)
V = 0
for i in range(len(X)):
V = V + P[i]*(X[i]-E)**2
return math.sqrt(V)
# Création de la liste des gainsmoyens pour N échantillons de taille n
def echantillonGains(mise, N, n):
echantillon = []
for i in range(N):
echantillon.append(gainMoyen(mise, n))
return echantillon
# Borne de l'intervalle
def bornes(E, sigma, n):
return E-2*sigma/math.sqrt(n),E+2*sigma/math.sqrt(n)
#Calcul de la proportion des cas où l’écart entre le gain moyen et l'espérance est inférieur ou égal à 2𝜎/√𝑛
def propPoint(echantillon, i, s):
filtre = [x for x in echantillon if x <= s and x >= i]
return len(filtre)/len(echantillon)
#Constantes
mise = 8.4
N = 100
n = 100
X = [mise, 6, -mise]
P = [1/8, 7/16, 7/16]
#Espérance et écart-type
E = esperance(X, P)
sigma = ecartType(X, P)
#Bornes de l'intervalle
i, s = bornes(E, sigma, n)
#Echantillon
echantillon = echantillonGains(mise, N, n)
#paramètres figure
fig, ax1 = plt.subplots(1, 1,figsize=(20, 6))
ax1.plot([0,N],[i,i],'r--',label='$\mu-2\sigma/\sqrt {n}$;$\mu+2\sigma/\sqrt {n}$')
ax1.plot([0,N],[E,E],'g--',label='$\mu$')
ax1.plot([0,N],[s,s],'r--')
points, = ax1.plot([],[],'bo')
ax1.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
def init():
points.set_data([], [])
return (points,)
def animate(i):
global echantillon
points.set_data([range(i+1),echantillon[:i+1]])
return (points,)
plt.close ()
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=N,init_func=init,blit=True)
# l'un ou l'autre
HTML(ani.to_jshtml())
#HTML(ani.to_html5_video())