Simulation d'un échantillonRépétition d'une épreuve de Bernoulli
from random import*
from math import *
def moyenne(L):
n = len(L)
m = 0
for i in range(0,n):
m = m+L[i]
return (1.0*m)/n
def sigma(L):
n = len(L)
e = 0
m = moyenne(L)
for i in range(0,n):
e = e +(L[i]-m)**2
return sqrt((1.0*e)/n)
def bernoulli(n,p,taille):
L = [0]*taille
for i in range(0,taille):
X = 0
for j in range(0,n):
ps = uniform(0,1)
c = 0
if ps < p:
c = 1
X = X+c
L[i] = X
return [L,moyenne(L),sigma(L)]
E = bernoulli(100,0.5,10)
print E[0]
print "Moyenne : ", E[1]
print "Ecart-type : ",E[2]
Répétition d'une variable aléatoire dont la loi est donnée sous forme d'un tableau
La variable aléatoire prend les valeurs $X$ suivant les probabilités $P$.
from random import*
from math import *
def moyenneP(A,B):
n = len(A)
m = 0
c = 0
for i in range(0,n):
c = c+B[i]
m = m +B[i]*A[i]
return (1.0*m)/c
def sigmaP(A,B):
n = len(A)
e = moyenneP(A,B)
s = 0
c = 0
for i in range(0,n):
c = c+B[i]
s = s + B[i]*(A[i]-e)**2
return sqrt( (1.0*s)/c )
def echantillon(X,P,taille):
n = len(P)
L = [0]*n
M = [0]*n
s = 0
for i in range(0,n):
s = s + P[i]
L[i] = s
for i in range(0,taille):
r = uniform(0,1)
k = 0
while r > L[k] and k < n:
k = k+1
M[k] = M[k]+1
return [M,moyenneP(X,M),sigmaP(X,M)]
X = [-10,1,5]
P = [0.2,0.2,0.6]
E = echantillon(X,P,100)
print X
print E[0]
print "Moyenne : ",E[1]
print "Ecart-type : ",E[2]