import numpy as np
import matplotlib.pyplot as plt
import random as rd

## Question 1
def exponentielle():
    return -np.log(1-rd.random())

## Question 2
def momentsEmpiriques(n):
    s,s2 = 0,0
    for k in range(n):
        x=exponentielle()
        s+=x
        s2+=x**2
    return s/n, s2/n - (s/n)

#
print(momentsEmpiriques(1000))

## Question 3
abs = [n for n in range(1,2000)]
ord = [momentsEmpiriques(n)[0] for n in abs]
plt.plot(abs,ord)
plt.show()


## Question 4
def mat_alea():
    N,P = 30,10000
    return np.array([[exponentielle() for j in range(P)] for i in range(N)])

## Question 5
def moyennes(n,mat):
    return np.sum(mat[:n],0)/n

## Question 6
N=30
mat = mat_alea()
for n in range(1,N+1):
    plt.clf()
    plt.grid()
    plt.axis([0,2,0,3])
    plt.hist(moyennes(n,mat),density=True,bins=80,label="n="+str(n))
    plt.legend(loc="upper right")
    plt.pause(.5)
plt.show()

## Question 7
N=30
mu, sigma = 1, 1
mat = mat_alea()
for n in range(1,N+1):
    plt.clf()
    plt.grid()
    plt.axis([-5,5,0,0.7])
    Mnetoiles = np.sqrt(n)*(moyennes(n,mat)-mu)/sigma
    plt.hist(Mnetoiles,density=True,bins=80,label="n="+str(n))
    x = np.linspace(-4,4,100)
    densiteN01=np.exp(-x**2/2)/np.sqrt(2*np.pi)
    plt.plot(x,densiteN01,color="red",label="densite de la loi N(0,1)")
    plt.legend(loc="upper right")
    plt.pause(.7)
plt.show()

## Question 8
N=30
mat = mat_alea()
for n in range(1,N+1):
    plt.clf()
    plt.grid()
    plt.axis([0,2,0,3])
    plt.hist(moyennes(n,mat),density=True,bins=80,label="n="+str(n))
    x = np.linspace(0,2,100)
    densiteN01=np.sqrt(n)*np.exp(-n*(x-1)**2/2)/np.sqrt(2*np.pi)
    plt.plot(x,densiteN01,color="red",label="densite de la loi N(1,1/n**0.5)")
    plt.legend(loc="upper right")
    plt.pause(.2)
plt.show()








