log, exp and float precision
math.log2, log10, log(x, base) and exp for logarithms and exponentials; int.bit_length() is the exact integer alternative to log2. Floats are IEEE-754 doubles, so compare with math.isclose and reach for fractions/decimal when exactness matters.
Syntax
import math
math.log2(8) # -> 3.0
math.log10(1000) # -> 3.0
math.log(81, 3) # -> 4.0 (may be 4.000000000000001 for some inputs)
math.log(math.e) # -> 1.0 natural log
math.exp(1) # -> 2.718281828459045
bit_length instead of log2
n = 37
n.bit_length() # -> 6 number of bits, == floor(log2(n)) + 1 for n > 0
n.bit_length() - 1 # -> 5 floor(log2(n)), exact
(n - 1).bit_length() # -> 6 ceil(log2(n)) for n >= 1
1 << (n - 1).bit_length() # -> 64 next power of two >= n
Power-of-two / power-of-k checks
def is_pow2(n: int) -> bool:
return n > 0 and n & (n - 1) == 0
def is_pow3(n: int) -> bool: # avoid round(math.log(n, 3))
while n > 1 and n % 3 == 0:
n //= 3
return n == 1
is_pow2(64), is_pow3(243) # -> (True, True)
Float precision and isclose
import math
0.1 + 0.2 == 0.3 # -> False
math.isclose(0.1 + 0.2, 0.3) # -> True rel_tol=1e-09 default
math.isclose(1e-12, 0, abs_tol=1e-9) # -> True need abs_tol near zero
float("inf"), -math.inf # sentinels for min/max
Exact arithmetic: fractions and decimal
from decimal import Decimal
from fractions import Fraction
Fraction(1, 3) + Fraction(1, 6) # -> Fraction(1, 2)
Decimal("0.1") + Decimal("0.2") # -> Decimal('0.3') build from str, not float