• [^] # Re: Code ?

    Posté par (site web personnel) . En réponse au journal Un article de "Pour la science" m'ayant amené à coder pour une petite vérification perso.... Évalué à 2. Dernière modification le 23 juillet 2021 à 08:07.

    J'avais corrigé la version GUI, mais j'avais oublié de reporter la correction dans la version CLI. Comme la simulation prend pas mal de temps avec les paramètres par défaut, j'ai rajouté l'affichage de la progression.

    Au final, ça donne :

    #!/usr/bin/env python3
    from random import randint
    from statistics import mean, median, pstdev
    import time
    NB_PEOPLE = 500
    AMOUNT_START = 2000
    NB_LOOP = 5000000
    RATE = 0.2
    DRATE = 0.05
    def pays(customer, seller, base):
     # no advantage for the poorest as no poorest
     if seller == customer:
     customer -= base * RATE
     seller += base * RATE
     # poorest receive the money so add DRATE in the transfer
     elif seller > customer:
     customer -= base * (RATE + DRATE)
     seller += base * (RATE + DRATE)
     # poorest pay the money so deduct DRATE in the transfer
     else:
     customer -= base * (RATE - DRATE)
     seller += base * (RATE - DRATE)
     return customer, seller
    people = [AMOUNT_START] * NB_PEOPLE
    timestamp = time.time_ns()
    for _ in range(0, NB_LOOP):
     # select two random people
     while True:
     a = randint(0, NB_PEOPLE - 1)
     b = randint(0, NB_PEOPLE - 1)
     if a != b:
     break
     base = min(people[a], people[b])
     people[a], people[b] = pays(people[a], people[b], base)
     if time.time_ns() - timestamp > 1500000000:
     print(f"{round(100*_/NB_LOOP)}%", end='\r')
     timestamp = time.time_ns()
    print(f"{round(100*_/NB_LOOP)}%", end='\r')
    # final, show the results
    people = sorted([int(p) for p in people])
    print(f"Last tranfert base: {base}.")
    print(f"people: {', '.join(str(p) for p in people)}")
    print(f"avg: {mean(people)} | median: {median(people)} | pstdev: {pstdev(people)}")

    Pour essayer en ligne :

    Zelbinium: pour la génération qui crée, pas celle qui scrolle...