NumPy log2()
The numpy.log2()
function computes the base-2 logarithm of each element in an input array.
Syntax
</>
Copy
numpy.log2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
Parameter | Type | Description |
---|---|---|
x | array_like | Input values for which base-2 logarithm is computed. |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array where the result is stored. If None, a new array is created. |
where | array_like, optional | Boolean mask specifying which elements to compute. Elements where where=False retain their original value. |
casting | str, optional | Defines the casting behavior when computing the logarithm. |
order | str, optional | Memory layout order of the output array. |
dtype | data-type, optional | Defines the data type of the output array. |
subok | bool, optional | Determines if subclasses of ndarray are preserved in the output. |
Return Value
Returns an array containing the base-2 logarithm of the input values. If the input is a scalar, a scalar is returned.
Examples
1. Computing Base-2 Logarithm of a Single Value
Here, we compute the base-2 logarithm of a single number.
</>
Copy
import numpy as np
# Define a number
num = 8
# Compute the base-2 logarithm
result = np.log2(num)
# Print the result
print("log2(8):", result)
Output:
log2(8): 3.0

2. Computing Base-2 Logarithm for an Array
We compute the base-2 logarithm for multiple values in an array.
</>
Copy
import numpy as np
# Define an array of numbers
values = np.array([1, 2, 4, 8, 16, 32])
# Compute the base-2 logarithm
log_values = np.log2(values)
# Print the results
print("Input values:", values)
print("Base-2 logarithm:", log_values)
Output:
Input values: [ 1 2 4 8 16 32]
Base-2 logarithm: [0. 1. 2. 3. 4. 5.]

3. Using the out
Parameter
Using an output array to store the logarithm results instead of creating a new array.
</>
Copy
import numpy as np
# Define an array of values
values = np.array([1, 2, 4, 8])
# Create an output array with the same shape
output_array = np.empty_like(values, dtype=float)
# Compute log2 and store the result in output_array
np.log2(values, out=output_array)
# Print the results
print("Computed log2 values:", output_array)
Output:
Computed log2 values: [0. 1. 2. 3.]

4. Using the where
Parameter
Using a condition to compute the logarithm only for selected elements.
</>
Copy
import numpy as np
# Define an array of numbers
values = np.array([1, 2, 4, 8, 16])
# Define a mask (compute log2 only where mask is True)
mask = np.array([True, False, True, False, True])
# Compute log2 where mask is True
result = np.log2(values, where=mask)
# Print the results
print("Computed log2 values with mask:", result)
Output:
Computed log2 values with mask: [0. 0. 2. 0. 4.]

The logarithm is computed only for elements where mask=True
. The other values remain unchanged.