log2(): Base-2 Logarithmic Calculations for Binary Data

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()
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer