NumPy cbrt()
The numpy.cbrt()
function computes the cube root of each element in an input array, element-wise.
Syntax
</>
Copy
numpy.cbrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
Parameter | Type | Description |
---|---|---|
x | array_like | The values whose cube roots are to be 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 cube root 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 the cube root of each element in the input array. If the input is a scalar, a scalar is returned.
Examples
1. Computing Cube Root of a Single Value
Here, we compute the cube root of a single numeric value.
</>
Copy
import numpy as np
# Define a number
num = 27
# Compute the cube root of the number
result = np.cbrt(num)
# Print the result
print("Cube root of 27:", result)
Output:
Cube root of 27: 3.0

2. Computing Cube Root for an Array
We compute the cube roots for multiple values in an array.
</>
Copy
import numpy as np
# Define an array of numbers
numbers = np.array([1, 8, 27, 64, 125])
# Compute the cube root of each number
cbrt_values = np.cbrt(numbers)
# Print the results
print("Input numbers:", numbers)
print("Cube root values:", cbrt_values)
Output:
Input numbers: [ 1 8 27 64 125]
Cube root values: [1. 2. 3. 4. 5.]

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 numbers
numbers = np.array([1, 64, 125, 216])
# Create an output array with the same shape
output_array = np.ndarray(shape=numbers.shape)
# Compute cube root and store in output_array
np.cbrt(numbers, out=output_array)
# Print the results
print("Computed cube root values:", output_array)
Output:
Computed cube root values: [1. 4. 5. 6.]

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

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