NumPy exp2()
The numpy.exp2()
function calculates 2 raised to the power of each element in an input array.
Syntax
</>
Copy
numpy.exp2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
Parameter | Type | Description |
---|---|---|
x | array_like | Input values. Each element will be used as an exponent to base 2. |
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 power function. |
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 with values of \(2^x\) computed element-wise. If the input is a scalar, a scalar is returned.
Examples
1. Computing 2^x
for a Single Value
Here, we compute \(2^x\) for a single value.
</>
Copy
import numpy as np
# Define an exponent value
x = 3
# Compute 2^x
result = np.exp2(x)
# Print the result
print("2^3 =", result)
Output:
2^3 = 8.0

2. Computing 2^x
for an Array of Values
We compute \(2^x\) for multiple values stored in an array.
</>
Copy
import numpy as np
# Define an array of exponent values
x_values = np.array([-2, -1, 0, 1, 2, 3])
# Compute 2^x for each element in the array
exp2_values = np.exp2(x_values)
# Print the results
print("Exponent values:", x_values)
print("2^x values:", exp2_values)
Output:
Exponent values: [-2 -1 0 1 2 3]
2^x values: [0.25 0.5 1. 2. 4. 8. ]

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

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

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