# -*- coding: utf-8 -*-
"""
TD n°7 --- L'essentiel de la simulation : approche frequentielle

Une section par diapo de EssentielTD7.pdf.
Le fichier s'execute jusqu'au bout. Les resultats changent a chaque
execution : les valeurs en commentaire sont des ordres de grandeur.
"""

import random


def titre(texte):
    print()
    print("=" * 60)
    print(texte)
    print("=" * 60)


# =====================================================================
titre("1. Simuler avec random.random()")
# =====================================================================

print(random.random())              # un reel de [0, 1[
print(random.random() < 0.3)        # True avec probabilite 0.3


def bernoulli(p):
    if random.random() < p:
        return 1
    return 0


def de():
    return int(6 * random.random()) + 1


print([bernoulli(0.3) for k in range(20)])
print([de() for k in range(20)])


# =====================================================================
titre("2. Estimer une probabilite : on compte")
# =====================================================================

def frequence_six(n):
    k = 0
    for i in range(n):
        if de() == 6:
            k = k + 1
    return k / n


for n in [10, 100, 1000, 10000, 100000]:
    print(n, frequence_six(n))
print("1/6 =", 1 / 6)


# Dans un calcul, True vaut 1 et False vaut 0 : autre ecriture possible
def frequence_six_bis(n):
    k = 0
    for i in range(n):
        k = k + (de() == 6)
    return k / n


print(frequence_six_bis(100000))


# =====================================================================
titre("3. Quelle precision ?")
# =====================================================================

for n in [100, 10000]:
    L = [frequence_six(n) for k in range(10)]
    print(n, min(L), max(L))
# Quand n est multiplie par 100, l'ecart a 1/6 est divise par environ 10.


# =====================================================================
titre("4. Combiner des evenements")
# =====================================================================

def somme_sept():
    return de() + de() == 7         # deux appels : deux des independants


def frequence_sept(n):
    k = 0
    for i in range(n):
        if somme_sept():
            k = k + 1
    return k / n


print(frequence_sept(100000), 6 / 36)


def fonctionne(theta):
    c = []
    for k in range(3):              # c[0], c[1], c[2]
        c.append(random.random() < theta)
    return c[0] and (c[1] or c[2])


def frequence_appareil(theta, n):
    k = 0
    for i in range(n):
        if fonctionne(theta):
            k = k + 1
    return k / n


for theta in [0.5, 0.9]:
    print(theta, frequence_appareil(theta, 100000), 2 * theta**2 - theta**3)


# Sans les parentheses : (c[0] and c[1]) or c[2], ce n'est plus l'appareil
def fonctionne_faux(theta):
    c = []
    for k in range(3):
        c.append(random.random() < theta)
    return c[0] and c[1] or c[2]


s = 0
for i in range(100000):
    if fonctionne_faux(0.5):
        s = s + 1
print("sans parentheses :", s / 100000, "(attendu : 0.375)")


# =====================================================================
titre("5. Estimer une esperance : on fait la moyenne")
# =====================================================================

def attente_six():
    nb = 1                          # le premier lancer est fait dans le test
    while de() != 6:
        nb = nb + 1
    return nb


def moyenne_attente(n):
    s = 0
    for i in range(n):
        s = s + attente_six()
    return s / n


print(moyenne_attente(100000), "(E(X) = 6)")


# =====================================================================
titre("6. Estimer une variance")
# =====================================================================

def nombre_succes(m, p):
    s = 0
    for k in range(m):
        s = s + bernoulli(p)
    return s


def moyenne_variance(m, p, n):
    s1 = 0                          # somme des X_i
    s2 = 0                          # somme des X_i**2
    for i in range(n):
        x = nombre_succes(m, p)     # on simule X UNE fois
        s1 = s1 + x
        s2 = s2 + x**2
    moy = s1 / n
    return moy, s2 / n - moy**2


print(moyenne_variance(10, 0.3, 100000), "(E(X) = 3, V(X) = 2.1)")


# =====================================================================
titre("7. Le piege : un tirage, un seul appel")
# =====================================================================

def tirage_faux():
    if random.random() < 1/2:       # u1
        return 1
    elif random.random() < 5/6:     # u2 : nouveau nombre, independant de u1
        return 2
    else:
        return 3


def tirage():
    u = random.random()             # un seul nombre
    if u < 1/2:                     # u dans [0, 1/2[
        return 1
    elif u < 5/6:                   # u dans [1/2, 5/6[
        return 2
    else:                           # u dans [5/6, 1[
        return 3


def frequences(n):
    c = [0, 0, 0]                   # c[0], c[1], c[2] : nombres de 1, de 2, de 3
    for i in range(n):
        y = tirage_faux()           # on garde le resultat dans une variable
        c[y - 1] = c[y - 1] + 1
    return [c[0] / n, c[1] / n, c[2] / n]


def frequences_bis(n):              # la meme chose avec tirage()
    c = [0, 0, 0]
    for i in range(n):
        y = tirage()
        c[y - 1] = c[y - 1] + 1
    return [c[0] / n, c[1] / n, c[2] / n]


print("tirage_faux :", frequences(100000), "(1/2, 5/12, 1/12)")
print("tirage      :", frequences_bis(100000), "(1/2, 1/3, 1/6)")
