Python math.log2() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Python 3.3+

Definition

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

ParameterDescription
xRequired positive number (int or float). Values <= 0 raise ValueError.

Return Value

Return ValueDescription
floatBase-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")

How It Works

  1. Exact binary powers. 1024 is 2**10 and 0.125 is 2**-3, yielding exact floats.
  2. Ceiling rounds up. One hundred distinct states need more than 6 bits, so math.ceil() returns 7.
  3. 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")

How It Works

  1. Guard zero probabilities. Filtering p > 0 skips zero probabilities before calling math.log2().
  2. Exact binary weights. Logarithms of 0.5, 0.25, and 0.125 are -1, -2, and -3.
  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.

python
import math

big = 2 ** 53
print(math.log2(big), math.log2(big + 1))
print(big.bit_length(), (big + 1).bit_length())

try:
    math.log2(-8)
except ValueError:
    print("log2 requires positive input")

How It Works

  1. Precision ceiling at 2**53. Adding one to 2**53 rounds away when converted to float, so log2 gives 53.0 for both.
  2. Exact bit_length(). Integer bit_length() counts the 54 bits directly without any float conversion.
  3. Domain guard. Passing -8 raises ValueError.

Frequently Asked Questions

math.log2() was introduced in Python 3.3.
math.log2() uses a dedicated base-2 algorithm and avoids division rounding errors on powers of two.
Use the built-in int method n.bit_length(), which stays exact for integers of any size.
0.0, because 2 ** 0 equals 1.
No. Any value <= 0 raises ValueError. Use cmath.log(x, 2) for complex values.

Next: math.modf()

Return the fractional and integer parts of x as floats.

modf() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful