W3docs

Matemáticas en Python

Aprende el módulo math de Python: constantes, redondeo, trigonometría, logaritmos, combinatoria y ejemplos prácticos con resultados reales.

Python incluye un módulo math integrado que da acceso a las funciones matemáticas de la biblioteca estándar de C. Este capítulo cubre:

  • Operadores aritméticos básicos que Python ofrece de forma nativa
  • Todas las constantes clave (pi, e, tau, inf, nan)
  • Ayudantes de redondeo, valor absoluto, potencia y raíz cuadrada
  • Funciones trigonométricas y conversión grados/radianes
  • Funciones logarítmicas y exponenciales
  • Ayudantes de teoría de números: gcd, factorial, isqrt, comb, perm
  • Inspección de punto flotante: isfinite, isinf, isnan, isclose

No se necesita instalación — con import math es suficiente.

Operadores aritméticos básicos

Python maneja la aritmética cotidiana con operadores integrados — no se requiere ningún módulo.

# 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  — exponentiation

El operador ** es la forma idiomática en Python para elevar un número a una potencia. Úsalo en lugar de math.pow() para entradas enteras — el resultado permanece como entero, mientras que math.pow() siempre devuelve un float.

Importar el módulo math

Para ir más allá de los operadores anteriores, importa math:

import math

También puedes importar nombres específicos para evitar el prefijo math.:

from math import sqrt, pi, factorial
print(sqrt(25))     # 5.0
print(pi)           # 3.141592653589793
print(factorial(5)) # 120

Prefiere import math en código de producción — así queda clara la fuente de cada función.

Constantes matemáticas

El módulo math define varias 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" sentinel

math.inf es útil como valor inicial cuando necesitas un centinela de "el mayor posible":

import math

best = math.inf
for value in [5, 3, 8, 1]:
    if value < best:
        best = value
print(best)  # 1

Redondeo y valor absoluto

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 float

La diferencia entre trunc y floor importa para números negativos:

import math

print(math.floor(-3.2))   # -4  — floor always rounds down
print(math.trunc(-3.2))   # -3  — trunc always rounds toward zero

Raíz cuadrada, potencia e hipotenusa

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() (añadido en Python 3.8) es la opción correcta cuando necesitas un resultado entero sin convertir desde float, por ejemplo al verificar cuadrados perfectos:

import math

n = 144
if math.isqrt(n) ** 2 == n:
    print(f"{n} is a perfect square")  # 144 is a perfect square

math.hypot() acepta más de dos argumentos desde Python 3.8 y calcula la norma euclídea en cualquier número de dimensiones:

import math

# 3-D distance from origin to (1, 2, 2)
print(math.hypot(1, 2, 2))  # 3.0

Factorial y ayudantes enteros

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 lanza un ValueError para entradas negativas y un TypeError para no enteros.

Combinatoria

Python 3.8 añadió math.comb y math.perm para reemplazar las fórmulas manuales de factorial:

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) es equivalente a n! / (k! * (n-k)!) pero es más rápido y evita valores intermedios grandes.

Funciones trigonométricas

El módulo math trabaja en radianes. Usa math.radians() para convertir grados primero.

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.0

Valores de ángulo comunes en radianes:

GradosExpresión en radianesValor en math
00
30°math.pi / 60.5236…
45°math.pi / 40.7854…
90°math.pi / 21.5708…
180°math.pi3.1416…

Las funciones trigonométricas inversas devuelven radianes:

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°)

Usa math.atan2(y, x) en lugar de math.atan(y/x) siempre que necesites el cuadrante correcto.

Funciones logarítmicas

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))

Prefiere math.log10 y math.log2 sobre math.log(x, 10) y math.log(x, 2) — las funciones dedicadas tienen mejor precisión numérica.

math.log lanza un ValueError para entradas no positivas:

import math

try:
    math.log(0)
except ValueError as e:
    print(e)   # math domain error

Funciones exponenciales

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) calcula e**x - 1 con mayor precisión cuando x está cerca de cero, lo cual importa en cálculos financieros y científicos.

Inspección de punto flotante

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))         # False

Comparar floats con isclose

Debido a la representación de punto flotante, las comparaciones de igualdad directa pueden fallar:

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 tolerance

math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0) devuelve True cuando |a - b| está dentro de la tolerancia relativa o absoluta. Usa siempre math.isclose en lugar de == al comparar floats calculados.

Referencia rápida

FunciónDevuelveEjemplo
math.sqrt(x)floatsqrt(9)3.0
math.isqrt(x)intisqrt(10)3
math.pow(x, y)floatpow(2, 8)256.0
math.floor(x)intfloor(3.9)3
math.ceil(x)intceil(3.1)4
math.trunc(x)inttrunc(-3.9)-3
math.fabs(x)floatfabs(-4)4.0
math.factorial(n)intfactorial(5)120
math.gcd(a, b)intgcd(12, 8)4
math.comb(n, k)intcomb(5, 2)10
math.perm(n, k)intperm(5, 2)20
math.log(x)floatlog(e)1.0
math.log10(x)floatlog10(100)2.0
math.log2(x)floatlog2(8)3.0
math.exp(x)floatexp(1)2.718…
math.sin(x)floatsin(pi/2)1.0
math.cos(x)floatcos(0)1.0
math.tan(x)floattan(pi/4)1.0
math.degrees(x)floatdegrees(pi)180.0
math.radians(x)floatradians(180)3.14…
math.hypot(*coords)floathypot(3, 4)5.0
math.isclose(a, b)boolisclose(0.1+0.2, 0.3)True
math.isfinite(x)boolisfinite(inf)False
math.isinf(x)boolisinf(inf)True
math.isnan(x)boolisnan(nan)True

Capítulos relacionados

Práctica

Práctica
Which math module function returns the largest integer less than or equal to a given number?
Which math module function returns the largest integer less than or equal to a given number?
Was this page helpful?