El módulo math reúne las funciones matemáticas que no están incluidas por defecto en el lenguaje: raíces, redondeos, trigonometría, logaritmos y más. Siempre empieza con import math.
Constantes
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
Raíces y potencias
print(math.sqrt(49)) # 7.0
print(math.pow(2, 10)) # 1024.0
print(2 ** 10) # 1024 (el operador ** devuelve un entero si puede)
print(math.hypot(3, 4)) # 5.0 (raíz de 3² + 4²)
math.sqrt falla con números negativos:
math.sqrt(-1)
# ValueError: math domain error
Redondeos
| Función | Qué hace | Con 3.7 | Con -3.7 |
|---|---|---|---|
math.floor(x) | entero hacia abajo | 3 | -4 |
math.ceil(x) | entero hacia arriba | 4 | -3 |
math.trunc(x) | quita la parte decimal | 3 | -3 |
round(x) | entero más cercano (función de Python) | 4 | -4 |
print(math.floor(3.7), math.ceil(3.7), math.trunc(3.7)) # 3 4 3
print(math.floor(-3.7), math.ceil(-3.7), math.trunc(-3.7)) # -4 -3 -3
Enteros: MCD, factorial y combinatoria
print(math.gcd(12, 18)) # 6 máximo común divisor
print(math.factorial(5)) # 120 (5 · 4 · 3 · 2 · 1)
print(math.comb(5, 2)) # 10 combinaciones: elegir 2 de 5 sin importar el orden
print(math.perm(5, 2)) # 20 permutaciones: elegir 2 de 5 importando el orden
El mínimo común múltiplo se calcula con la fórmula a * b // math.gcd(a, b).
Logaritmos
print(math.log(math.e)) # 1.0 logaritmo natural
print(math.log10(1000)) # 3.0
print(math.log2(8)) # 3.0
Trigonometría: ¡en radianes!
Las funciones sin, cos y tan trabajan con radianes, no con grados. Para convertir usa math.radians y math.degrees:
angulo = math.radians(90)
print(round(math.sin(angulo), 2)) # 1.0
print(math.degrees(math.pi)) # 180.0
Comparar decimales con isclose
Los decimales se guardan con pequeños errores, así que comparar con == puede fallar:
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True
Practica en Hipotenusa, Área y longitud del círculo, Suelo, techo y truncado, Máximo común divisor y mínimo común múltiplo y Combinaciones y permutaciones.