Python math.log2() function


The math.log2() function in Python is used to compute the base-2 logarithm of a given number. It is part of the math module, which provides access to various mathematical functions.

Syntax

import math result = math.log2(x)
  • x: A positive numeric expression (integer or float) for which you want to calculate the base-2 logarithm.

Return Value

  • Returns the logarithm of x to base 2 as a float.
  • If x is less than or equal to zero, a ValueError will be raised.

Examples

  1. Calculating the base-2 logarithm of a positive integer:

    import math result = math.log2(8) print(result) # Output: 3.0 (because 2^3 = 8)
  2. Calculating the base-2 logarithm of a decimal:

    result = math.log2(0.5) print(result) # Output: -1.0 (because 2^-1 = 0.5)
  3. Calculating the logarithm of a larger number:

    result = math.log2(32) print(result) # Output: 5.0 (because 2^5 = 32)
  4. Handling values less than or equal to zero: If you try to calculate the logarithm of a non-positive number, a ValueError will be raised.

    try: result = math.log2(-4) except ValueError as e: print(e) # Output: math domain error
  5. Using math.log2() in expressions: You can use math.log2() in combination with other mathematical operations:

    value = 64 result = math.log2(value) + 1 print(result) # Output: 7.0

Summary

  • The math.log2() function computes the logarithm of a positive number to base 2.
  • It returns a float representing the logarithmic value.
  • This function is commonly used in computer science and information theory, particularly in contexts like calculating binary tree depths, analyzing algorithm complexity, and data encoding.