80 lines
2.0 KiB
Python
80 lines
2.0 KiB
Python
|
#!/usr/bin/env python3
|
||
|
import random
|
||
|
import numpy as np
|
||
|
import matplotlib.pyplot as plt
|
||
|
|
||
|
|
||
|
class Question:
|
||
|
def __init__(self,i=1, l=0, n=''):
|
||
|
self.name=n
|
||
|
self.level=l
|
||
|
self.number=i
|
||
|
def __enter__(self):
|
||
|
print('\n' + (self.level*2)*' ' + f"-> {self.number}. : {self.name} -- Début")
|
||
|
return self
|
||
|
def __exit__(self, exc_type, exc_value, exc_traceback):
|
||
|
print((self.level*2)*' ' + f"<- {self.number}. : {self.name} -- Fin\n")
|
||
|
with Question(1):
|
||
|
def tirer(n):
|
||
|
item = 0
|
||
|
for _ in range(n):
|
||
|
if random.random()<.5:
|
||
|
item +=1
|
||
|
return item
|
||
|
|
||
|
def proportion(n , N, k):
|
||
|
s = 0
|
||
|
for i in range(N):
|
||
|
if tirer(n) == k:
|
||
|
s += 1
|
||
|
return s/N
|
||
|
print('proportion(10, 100, 1) :', proportion(10, 100, 5))
|
||
|
n = 10
|
||
|
N = 100
|
||
|
plt.figure(0)
|
||
|
x = np.asarray(range(n+1))
|
||
|
y = np.asarray([proportion(n, N, k) for k in x])
|
||
|
plt.plot(x, y)
|
||
|
|
||
|
|
||
|
def binom(k, n):
|
||
|
return np.math.factorial(n)/(np.math.factorial(k)*np.math.factorial(n-k))
|
||
|
plt.figure(1)
|
||
|
x = np.asarray(range(n+1))
|
||
|
y = np.asarray([binom(k, n) for k in x])
|
||
|
plt.plot(x, y)
|
||
|
|
||
|
#Version avec une proportion p :
|
||
|
def tirer2(n, p):
|
||
|
item = 0
|
||
|
for _ in range(n):
|
||
|
if random.random()<p:
|
||
|
item +=1
|
||
|
return item
|
||
|
|
||
|
def proportion2(n, p, N, k):
|
||
|
s = 0
|
||
|
for i in range(N):
|
||
|
if tirer2(n, p) == k:
|
||
|
s += 1
|
||
|
return s/N
|
||
|
|
||
|
p = .3
|
||
|
print('proportion2(10, p, 100, 1) :', proportion2(10, p, 100, 5))
|
||
|
n = 10
|
||
|
N = 100
|
||
|
plt.figure(2)
|
||
|
x = np.asarray(range(n+1))
|
||
|
y = np.asarray([proportion2(n, p, N, k) for k in x])
|
||
|
plt.plot(x, y)
|
||
|
|
||
|
|
||
|
def prop(k, n, p):
|
||
|
return binom(k, n) * (p**k) * (1-p)**(n-k)
|
||
|
plt.figure(3)
|
||
|
x = np.asarray(range(n+1))
|
||
|
y = np.asarray([prop(k, n, p) for k in x])
|
||
|
plt.plot(x, y)
|
||
|
plt.show()
|
||
|
|