Python Math
Découvrez le module math de Python : constantes, arrondi, trigonométrie, logarithmes, combinatoire et exemples pratiques avec résultats réels.
Python est livré avec un module math intégré qui vous donne accès aux fonctions mathématiques de la bibliothèque standard C. Ce chapitre couvre :
- Les opérateurs arithmétiques de base fournis nativement par Python
- Toutes les constantes clés (
pi,e,tau,inf,nan) - Les fonctions d'arrondi, de valeur absolue, de puissance et de racine carrée
- Les fonctions trigonométriques et la conversion degrés/radians
- Les fonctions logarithmiques et exponentielles
- Les fonctions de théorie des nombres :
gcd,factorial,isqrt,comb,perm - L'inspection des nombres à virgule flottante :
isfinite,isinf,isnan,isclose
Aucune installation n'est nécessaire — import math suffit.
Opérateurs arithmétiques de base
Python gère l'arithmétique courante avec des opérateurs intégrés — aucun module requis.
# Integer and float arithmetic
print(2 + 3) # 5 — addition
print(5 - 2) # 3 — subtraction
print(3 * 4) # 12 — multiplication
print(10 / 2) # 5.0 — true division (always returns float)
print(10 // 3) # 3 — floor division (rounds toward negative infinity)
print(10 % 3) # 1 — modulo (remainder)
print(2 ** 8) # 256 — exponentiationL'opérateur ** est la façon idiomatique Python d'élever un nombre à une puissance. Utilisez-le plutôt que math.pow() pour les entrées entières — le résultat reste un entier, alors que math.pow() retourne toujours un float.
Importer le module math
Pour tout ce qui va au-delà des opérateurs ci-dessus, importez math :
import mathVous pouvez également importer des noms spécifiques pour éviter le préfixe math. :
from math import sqrt, pi, factorial
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
print(factorial(5)) # 120Préférez import math dans le code de production — cela rend l'origine de chaque fonction évidente.
Constantes mathématiques
Le module math définit plusieurs constantes :
import math
print(math.pi) # 3.141592653589793 — ratio of circumference to diameter
print(math.e) # 2.718281828459045 — base of the natural logarithm
print(math.tau) # 6.283185307179586 — 2 * pi (full circle in radians)
print(math.inf) # inf — positive infinity
print(math.nan) # nan — "not a number" sentinelmath.inf est utile comme valeur de départ lorsque vous avez besoin d'une sentinelle représentant la « plus grande valeur possible » :
import math
best = math.inf
for value in [5, 3, 8, 1]:
if value < best:
best = value
print(best) # 1Arrondi et valeur absolue
import math
print(math.floor(3.7)) # 3 — round toward negative infinity
print(math.ceil(3.2)) # 4 — round toward positive infinity
print(math.trunc(3.9)) # 3 — strip the decimal (toward zero)
print(math.trunc(-3.9)) # -3 — note: trunc(-3.9) != floor(-3.9)
print(math.fabs(-5.3)) # 5.3 — absolute value, always returns float
print(abs(-5)) # 5 — built-in abs() works for int and floatLa différence entre trunc et floor est importante pour les nombres négatifs :
import math
print(math.floor(-3.2)) # -4 — floor always rounds down
print(math.trunc(-3.2)) # -3 — trunc always rounds toward zeroRacine carrée, puissance et hypoténuse
import math
print(math.sqrt(25)) # 5.0 — square root (returns float)
print(math.isqrt(17)) # 4 — integer square root (floor, returns int)
print(math.pow(2, 10)) # 1024.0 — power, always returns float
print(2 ** 10) # 1024 — integer exponentiation, stays int
print(math.hypot(3, 4)) # 5.0 — Euclidean distance sqrt(3²+4²)math.isqrt() (ajouté en Python 3.8) est le bon choix lorsque vous avez besoin d'un résultat entier sans conversion depuis un float, par exemple pour vérifier des carrés parfaits :
import math
n = 144
if math.isqrt(n) ** 2 == n:
print(f"{n} is a perfect square") # 144 is a perfect squaremath.hypot() accepte plus de deux arguments depuis Python 3.8 et calcule la norme euclidienne dans n'importe quel nombre de dimensions :
import math
# 3-D distance from origin to (1, 2, 2)
print(math.hypot(1, 2, 2)) # 3.0Factorielle et fonctions entières
import math
print(math.factorial(5)) # 120 — 5! = 5*4*3*2*1
print(math.factorial(0)) # 1 — 0! is defined as 1
print(math.gcd(48, 18)) # 6 — greatest common divisor
print(math.lcm(4, 6)) # 12 — least common multiple (Python 3.9+)math.factorial lève une ValueError pour les entrées négatives et une TypeError pour les non-entiers.
Combinatoire
Python 3.8 a ajouté math.comb et math.perm pour remplacer les formules de factorielle manuelles :
import math
# Number of ways to choose 2 items from 5 (order does not matter)
print(math.comb(5, 2)) # 10
# Number of ways to arrange 2 items from 5 (order matters)
print(math.perm(5, 2)) # 20
# All permutations of 5 items
print(math.perm(5)) # 120 — same as factorial(5)comb(n, k) est équivalent à n! / (k! * (n-k)!) mais plus rapide et évite les grandes valeurs intermédiaires.
Fonctions trigonométriques
Le module math fonctionne en radians. Utilisez math.radians() pour convertir d'abord les degrés.
import math
angle_deg = 30
angle_rad = math.radians(angle_deg) # 0.5235987755982988
print(math.sin(angle_rad)) # 0.49999999999999994 (~0.5)
print(math.cos(angle_rad)) # 0.8660254037844387 (~√3/2)
print(math.tan(angle_rad)) # 0.5773502691896256 (~1/√3)
# Convert radians back to degrees
print(math.degrees(math.pi)) # 180.0Valeurs d'angles courants en radians :
| Degrés | Expression en radians | Valeur math |
|---|---|---|
| 0° | 0 | 0 |
| 30° | math.pi / 6 | 0.5236… |
| 45° | math.pi / 4 | 0.7854… |
| 90° | math.pi / 2 | 1.5708… |
| 180° | math.pi | 3.1416… |
Les fonctions trigonométriques inverses retournent des radians :
import math
print(math.asin(0.5)) # 0.5235987755982988 (= pi/6 = 30°)
print(math.acos(0.5)) # 1.0471975511965976 (= pi/3 = 60°)
print(math.atan(1.0)) # 0.7853981633974483 (= pi/4 = 45°)
# atan2(y, x) handles all quadrants correctly
print(math.atan2(1, -1)) # 2.356… (135° — second quadrant)
print(math.atan2(-1, -1)) # -2.356… (225° / -135°)Utilisez math.atan2(y, x) plutôt que math.atan(y/x) chaque fois que vous avez besoin du quadrant correct.
Fonctions logarithmiques
import math
print(math.log(math.e)) # 1.0 — natural log (base e)
print(math.log(100, 10)) # 2.0 — log with explicit base
print(math.log10(1000)) # 3.0 — base-10 log (more accurate than log(x, 10))
print(math.log2(8)) # 3.0 — base-2 log (more accurate than log(x, 2))Préférez math.log10 et math.log2 à math.log(x, 10) et math.log(x, 2) — les fonctions dédiées offrent une meilleure précision numérique.
math.log lève une ValueError pour les entrées non positives :
import math
try:
math.log(0)
except ValueError as e:
print(e) # math domain errorFonctions exponentielles
import math
print(math.exp(1)) # 2.718281828459045 — e¹
print(math.exp(0)) # 1.0 — e⁰
print(math.exp(2)) # 7.38905609893065 — e²
# For small x, expm1(x) is more accurate than exp(x) - 1
print(math.expm1(1e-10)) # 1.00000000005e-10 (accurate)
print(math.exp(1e-10) - 1) # 1.000000082740371e-10 (slightly less precise)math.expm1(x) calcule e**x - 1 avec une plus grande précision lorsque x est proche de zéro, ce qui est important dans les calculs financiers et scientifiques.
Inspection des nombres à virgule flottante
import math
print(math.isfinite(1.0)) # True
print(math.isfinite(math.inf)) # False
print(math.isfinite(math.nan)) # False
print(math.isinf(math.inf)) # True
print(math.isinf(-math.inf)) # True
print(math.isinf(1e308)) # False — large but finite
print(math.isnan(math.nan)) # True
print(math.isnan(float('nan')))# True
print(math.isnan(0.0)) # FalseComparer des flottants avec isclose
En raison de la représentation en virgule flottante, les comparaisons d'égalité directes peuvent échouer :
print(0.1 + 0.2 == 0.3) # False — floating-point rounding
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True — within default tolerancemath.isclose(a, b, rel_tol=1e-09, abs_tol=0.0) retourne True lorsque |a - b| est dans la tolérance relative ou absolue. Utilisez toujours math.isclose plutôt que == pour comparer des flottants calculés.
Référence rapide
| Fonction | Retourne | Exemple |
|---|---|---|
math.sqrt(x) | float | sqrt(9) → 3.0 |
math.isqrt(x) | int | isqrt(10) → 3 |
math.pow(x, y) | float | pow(2, 8) → 256.0 |
math.floor(x) | int | floor(3.9) → 3 |
math.ceil(x) | int | ceil(3.1) → 4 |
math.trunc(x) | int | trunc(-3.9) → -3 |
math.fabs(x) | float | fabs(-4) → 4.0 |
math.factorial(n) | int | factorial(5) → 120 |
math.gcd(a, b) | int | gcd(12, 8) → 4 |
math.comb(n, k) | int | comb(5, 2) → 10 |
math.perm(n, k) | int | perm(5, 2) → 20 |
math.log(x) | float | log(e) → 1.0 |
math.log10(x) | float | log10(100) → 2.0 |
math.log2(x) | float | log2(8) → 3.0 |
math.exp(x) | float | exp(1) → 2.718… |
math.sin(x) | float | sin(pi/2) → 1.0 |
math.cos(x) | float | cos(0) → 1.0 |
math.tan(x) | float | tan(pi/4) → 1.0 |
math.degrees(x) | float | degrees(pi) → 180.0 |
math.radians(x) | float | radians(180) → 3.14… |
math.hypot(*coords) | float | hypot(3, 4) → 5.0 |
math.isclose(a, b) | bool | isclose(0.1+0.2, 0.3) → True |
math.isfinite(x) | bool | isfinite(inf) → False |
math.isinf(x) | bool | isinf(inf) → True |
math.isnan(x) | bool | isnan(nan) → True |
Chapitres connexes
- Python Numbers — types entier, float et complexe
- Python Operators — opérateurs arithmétiques, de comparaison et logiques
- Python Variables — stocker et nommer des valeurs
- Python Modules — comment importer et utiliser des modules