NumPy cbrt() Function:
Numpy cube root: The cube root of a specified number is calculated using the cbrt() function of the NumPy module.
Syntax:
numpy.cbrt(x, out=None)
Parameters
x: This is required. It is an array (array-like) having elements for which the cube root values are calculated.
out: This is optional. It is the location where the result will be saved. It must have a shape that the inputs broadcast to if it is provided. If None or not given, a newly allocated array is returned.
Return Value:
The cube root value of each element of x is returned.
NumPy cbrt() Function in Python
Example1
Approach:
- Import numpy module using the import keyword.
- Pass some random list as an argument to the array() function to create an array.
- Store it in a variable.
- Print the above-given array.
- Pass the above-given array as an argument to the cbrt() function of the numpy module to get the cube root values of given array elements.
- Store it in another variable.
- Print the cube root values of given array elements.
- The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array.
# Store it in a variable.
gvn_arry = np.array([27, 80, 25, 125, 1000])
# Pass the above given array as an argument to the cbrt() function of the
# numpy module to get the cube root values of given array elements
# Store it in another variable.
rslt = np.cbrt(gvn_arry)
# Print the cube root values of given array elements
print("The cube root values of given array elements = ")
print(rslt)
Output:
The cube root values of given array elements = [ 3. 4.30886938 2.92401774 5. 10. ]
Example2 – (For Complex Numbers)
The cbrt() function of the NumPy module does not support complex numbers as shown below.
Approach:
- Import numpy module using the import keyword.
- Give some random complex as static input and store it in a variable.
- Pass the above complex number as an argument to the cbrt() function of the numpy module to get the cube root of it.
- Store it in a variable.
- Print the cube root of the given complex number.
Below is the implementation:
# Import numpy module using the import keyword
import numpy as np
# Give some random complex as static input and store it in a variable.
gvn_num = 2 + 4j
# Pass the above complex number as an argument to the cbrt() function of the
# numpy module to get the cube root of it.
# Store it in a variable.
rslt = np.cbrt(gvn_num)
# Print the cube root of the given complex number
print("The cube root of the given complex number = ")
print(rslt)
Output:
TypeError: ufunc 'cbrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''