Aller au contenu

Numériques#

courant

Module math#

import math
math.sqrt(16)          # 4.0
math.pow(2, 10)          # 1024.0 (toujours float, contrairement à **)
math.floor(3.7); math.ceil(3.2)
math.trunc(3.7)           # 3 (troncature vers 0)
math.pi; math.e
math.log(8, 2)             # 3.0 (log base 2)
math.log2(8); math.log10(100)
math.factorial(5)            # 120
math.gcd(12, 18)               # 6
math.hypot(3, 4)                 # 5.0
math.isclose(0.1 + 0.2, 0.3)       # True (comparaison flottante sûre)

Arithmétique flottante (norme IEEE 754)

En binaire, 0.1 + 0.2 donne 0.30000000000000004. Par conséquent, l'égalité stricte 0.1 + 0.2 == 0.3 vaut False. En calcul numérique et ingénierie, ne jamais utiliser == entre deux flottants : toujours utiliser math.isclose(a, b, rel_tol=1e-9) ou une tolérance abs(a - b) < 1e-6.

Module statistics#

import statistics as stats
stats.mean([1, 2, 3, 4])       # 2.5
stats.median([1, 2, 3, 4])       # 2.5
stats.mode([1, 1, 2, 3])          # 1
stats.stdev([1, 2, 3, 4])           # écart-type (échantillon)
stats.variance([1, 2, 3, 4])

Module random#

import random
random.random()             # float dans [0.0, 1.0)
random.randint(1, 6)          # int dans [1, 6] (inclusif)
random.choice(["a", "b"])       # un élément au hasard
random.sample([1, 2, 3, 4], 2)    # 2 éléments distincts au hasard
random.shuffle(liste)               # mélange en place
random.uniform(1.5, 3.5)              # float dans [1.5, 3.5]
random.seed(42)                         # reproductibilité

Précision décimale exacte : decimal#

from decimal import Decimal
Decimal("0.1") + Decimal("0.2")   # Decimal('0.3') exact, utile pour les montants monétaires

Fractions exactes : fractions#

from fractions import Fraction
Fraction(1, 3) + Fraction(1, 6)   # Fraction(1, 2)