Return the base 2 logarithm for complex value input in Python

The numpy.log2() function computes the base-2 logarithm of array elements. When working with complex numbers, it returns complex logarithmic values using the formula log?(z) = ln(z) / ln(2).

Syntax

numpy.log2(x, out=None, where=True)

Parameters

The function accepts the following parameters ?

  • x ? Input array or scalar value
  • out ? Optional output array to store results
  • where ? Condition to broadcast over input

Example with Complex Numbers

Here's how to calculate base-2 logarithm for complex values ?

import numpy as np

# Create an array with complex numbers
arr = np.array([0+1.j, 1, 2+0.j])

# Display the array
print("Array...")
print(arr)

# Get array properties
print("\nArray type:", arr.dtype)
print("Array dimension:", arr.ndim)
print("Array shape:", arr.shape)

# Calculate base-2 logarithm
result = np.log2(arr)
print("\nBase-2 logarithm:")
print(result)
Array...
[0.+1.j 1.+0.j 2.+0.j]

Array type: complex128
Array dimension: 1
Array shape: (3,)

Base-2 logarithm:
[0.        +2.26618007j 0.        +0.j         1.        +0.j        ]

Understanding Complex Logarithms

For complex numbers, the logarithm has both real and imaginary parts ?

import numpy as np

# Different complex number examples
complex_nums = np.array([1+1j, -1+0j, 0+2j, 4+0j])

print("Complex numbers:")
print(complex_nums)

print("\nBase-2 logarithms:")
log_result = np.log2(complex_nums)
print(log_result)

print("\nReal parts:")
print(log_result.real)

print("\nImaginary parts:")
print(log_result.imag)
Complex numbers:
[ 1.+1.j -1.+0.j  0.+2.j  4.+0.j]

Base-2 logarithms:
[0.5       +2.26618007j 0.        +4.53236014j 1.        +2.26618007j
 2.        +0.j        ]

Real parts:
[0.5 0.  1.  2. ]

Imaginary parts:
[2.26618007 4.53236014 2.26618007 0.        ]

Key Points

  • For pure real positive numbers, the result has zero imaginary part
  • For pure imaginary numbers, the result has both real and imaginary components
  • The function handles arrays of any shape containing complex values
  • Results are returned as complex128 data type

Conclusion

The numpy.log2() function efficiently computes base-2 logarithms for complex numbers, returning results with appropriate real and imaginary parts. This is useful in signal processing and mathematical computations involving complex analysis.

Updated on: 2026-03-26T19:11:58+05:30

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements