Python math.log2() - Logarithm to Base 2
Python math.log2()
math.log2(x) function returns the logarithm of x to base 2.
Syntax
The syntax to call log2() function is
math.log2(x)where
| Parameter | Required | Description |
|---|---|---|
| x | Yes | A numeric value. The value must be greater than 0. |
If x is an invalid value, such as a negative value, then log2() raises ValueError.
Examples
In the following program, we find the logarithm of 8 to base 2, using log2() function of math module.
Python Program
import math
x = 8
result = math.log2(x)
print('log2(x) :', result)Output
log2(x) : 3.0Logarithm of a negative number to base 2.
Python Program
import math
x = -1
result = math.log2(x)
print('log2(x) :', result)Output
ValueError: math domain errorLogarithm of infinity.
Python Program
import math
x = math.inf
result = math.log2(x)
print('log2(x) :', result)Output
log2(x) : infLogarithm of 1024 to base 2.
Python Program
import math
x = 1024
result = math.log2(x)
print('log2(x) :', result)Output
log2(x) : 10.0Summary
In this Python Examples tutorial, we learned the syntax of, and examples for math.log2() function.