Numpy.cbrt() Method Example | How to Use numpy.cbrt() Method in Python

Numpy cbrt() is a mathematical method that is used to find the cube root of every element in a given array. To calculate cube root in Python, use the numpy cbrt() method.

Syntax

numpy.cbrt(arr, out = None, ufunc ‘cbrt’) : 

Parameters :

arr  : [array_like] Input array or object
        whose elements, we need to square.

Return :

  • An array with cube root of x for all x i.e. array elements 

Example 1: How to Use numpy.cbrt() method

import numpy as np

arr1 = [1, 8, 27, 64]
arr2 = np.cbrt(arr1)
print(arr2)

Output

[1. 2. 3. 4.]

Example 2: If an array element is a complex number

import numpy as np

arr1 = [3+4j]
arr2 = np.cbrt(arr1)
print(arr2)

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''

The interpreter throws the TypeError: ufunc ‘cbrt’ unsupported for the input types, and the inputs could not safely coerced to any supported types.

Example 3: Plotting the np.cbrt() method

import numpy as np
import matplotlib.pyplot as plt

# Create an array of x values from -10 to 10
x = np.linspace(-10, 10, 400)

# Compute the cube root of these values
y = np.cbrt(x)

# Create a new figure
plt.figure()

# Plot x against the cube root of x
plt.plot(x, y)

# Set the title and labels for the plot
plt.title('Cube Root Function')
plt.xlabel('x')
plt.ylabel('Cube Root of x')

# Display the plot
plt.show()

Thanks for reading !!!

#numpy #python

Numpy.cbrt() Method Example | How to Use numpy.cbrt() Method in Python
32.50 GEEK