Mathématiques en première générale – Algorithmes

\(\textrm{E}(X)\), \(V(X)\), \(\sigma(X)\)

Algorithmes renvoyant l'espérance, la variance ou l'écart-type d'une variable aléatoire
def parametres(X) :
    e = sum(X[x] * x for x in X)
    v = sum(X[x] * x ** 2 for x in X) - e ** 2
    return e, v
    
from fractions import Fraction
def d2des(n) :
    compte = {}
    for i in range(n) :
        for j in range(n) :
            x = abs(i - j)
            if x in compte :
                compte[x] += 1
            else :
                compte[x] = 1
    return {x: Fraction(compte[x], n ** 2) for x in compte}

from math import sqrt
def run(X) :
    for x in sorted(X) :
        print("P(x={}) = {} ≈ {}".format(x, X[x], float(X[x])))
    e, v = parametres(X)
    print("E(X) = {} ≈ {}".format(e, float(e)))
    print("V(X) = {} ≈ {}".format(v, float(v)))
    print("σ(X) ≈ {}".format(sqrt(float(v))))

run(d2des(6))
P(x=0) = 1/6 ≈ 0.16666666666666666
P(x=1) = 5/18 ≈ 0.2777777777777778
P(x=2) = 2/9 ≈ 0.2222222222222222
P(x=3) = 1/6 ≈ 0.16666666666666666
P(x=4) = 1/9 ≈ 0.1111111111111111
P(x=5) = 1/18 ≈ 0.05555555555555555
E(X) = 35/18 ≈ 1.9444444444444444
V(X) = 665/324 ≈ 2.052469135802469
σ(X) ≈ 1.4326441064697364
Lionel Avon