math.log2(x) returns the base-2 logarithm of x as a float. It is more accurate than math.log(x, 2) and returns exact values for powers of two.
Added in Python 3.3, it pairs with math.exp2() (Python 3.11+). For exact bit counts on very large integers without floating-point limits, use the integer method n.bit_length().
math.log2() is a function in Python's standard math module: import it with import math and call math.log2(...), or import the name directly with from math import log2.
Syntax
Import math and pass a positive real number.
python
import math
bits = math.log2(x)
Call
What it does
math.log2(8)
Returns 3.0.
math.log2(1024)
Returns 10.0.
math.log2(0.125)
Returns -3.0.
math.log2(0)
Raises ValueError: domain error.
Added in Python 3.3. For integer bit widths, prefer n.bit_length() over math.floor(math.log2(n)) + 1.
Function signatures
python
math.log2(x, /)
# added in Python 3.3; returns float log base 2 of x
Parameters
Parameter
Description
x
Required positive number (int or float). Values <= 0 raise ValueError.
Return Value
Return Value
Description
float
Base-2 logarithm of x. Returns inf for inf and nan for nan.
Python Examples
Example 1 — Count Binary Tree Levels and Address Bits
Compute exact binary powers and round up with math.ceil() to find bit widths.
python
import math
print(math.log2(1024), math.log2(0.125))
for states in [2, 16, 100, 1000]:
bits = math.ceil(math.log2(states))
print(f"{states:>4} states -> {bits:>2} bits")
Output
10.0 -3.0
2 states -> 1 bits
16 states -> 4 bits
100 states -> 7 bits
1000 states -> 10 bits
How It Works
Exact binary powers.1024 is 2**10 and 0.125 is 2**-3, yielding exact floats.
Ceiling rounds up. One hundred distinct states need more than 6 bits, so math.ceil() returns 7.
Integer bit counts. Combining log2() with ceil() tells you how many address bits cover a capacity.
Example 2 — Compute Shannon Entropy of a Probability Distribution
Sum -p * math.log2(p) across outcomes to measure information in bits.
python
import math
probs = [0.5, 0.25, 0.125, 0.125]
entropy = math.fsum(-p * math.log2(p) for p in probs if p > 0)
print(f"entropy: {entropy:.4f} bits")
Output
entropy: 1.7500 bits
How It Works
Guard zero probabilities. Filtering p > 0 skips zero probabilities before calling math.log2().
Exact binary weights. Logarithms of 0.5, 0.25, and 0.125 are -1, -2, and -3.
Accurate total. Using math.fsum() accumulates the weighted bits to exact 1.7500 bits.
Example 3 — Compare bit_length() With log2() on Large Integers
See where 64-bit floats lose precision past 2**53 and catch invalid inputs.