log2(): Base-2 Logarithmic Calculations for Binary Data
Python Math functions
log2(x) returns logarithm of x with base 2
import math
print(math.log2(2)) # 1.0
print(math.log2(4)) # 2.0
print(math.log2(5)) # 2.321928094887362
Using negative number
For any value less than or equal to 0 , we will get ValueError
import math
print(math.log2(-2))
Above code will generate error.
Use Case: Data Size Calculation: To calculate how many bits are needed to store a number:
print(math.log2(1024) + 1) # Output: 11.0
Example 2: Error Handling for Negative Numbers
The `log2()` function raises a ValueError if `x` is 0 or negative, as log values are undefined for such inputs.
import math
try:
print(math.log2(-4))
except ValueError as e:
print("Error:", e)
Output
Error: math domain error
Example 3: Log2 in Binary Tree Depth Calculation
In binary trees, the depth (number of levels) for a full tree can be calculated using `log2()`.
import math
nodes = 8
depth = math.log2(nodes + 1)
print("Tree depth:", int(depth))
Output
Tree depth: 3
Applications of log2()
Computer Science : To calculate data storage sizes, binary tree depths, and algorithm complexity.
Information Theory : To determine entropy and information content.
Signal Processing : Logarithmic scaling of binary data for processing.
« log
modf()
Author & Instructor at
plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com