How to Find Cube Root in Python

Here are three ways to find a cube root in Python.

  1. Using the math.pow()
  2. Using the exponentiation operator(**)
  3. Using the numpy.cbrt()

Method 1: Using the math.pow() function

To find the cube root of a number using math.pow() function, you can raise the number to the power of (1/3).

import math

number = 27

# Calculate the cube root using math.pow()
cube_root = math.pow(number, 1/3)

print("Cube root of", number, "is:", cube_root)

Output

Cube root of 27 is: 3.0

Method 2: Using the exponentiation operator

You can use the simple math equation: x ** (1. / 3) to calculate the cube root of a number in Python. It calculates the (floating-point) cube root of x.

It is a simple math equation that takes the cube root of x, rounds it to the nearest integer, raises it to the third power, and checks whether the result equals x.

x = 27

cr = x ** (1./3.)

print(cr)

Output

3.0

Finding a cube root of a negative number in Python

To find the cube root of a negative number in Python, first, use the abs() function, and then you can use the simple math equation to calculate the cube root.

We can not find the cube root of the negative numbers the way we calculated for the above method. For example, the cube root of integer -27 should be -3, but Python returns 1.5000000000000004+2.598076211353316j.

def cuberoot(x):
  if x < 0:
    x = abs(x)
    cube_root = x**(1/3)*(-1)
  else:
    cube_root = x**(1/3)
    return cube_root


print(cuberoot(27))
print(round(cuberoot(-27)))

Output

3.0
-3

Method 3: Using the Numpy cbrt() function

The np.cbrt() function is used to calculate the cube root of a number or an array of numbers. To calculate a cube root of a number or array of numbers in numpy, you can use the np.cbrt() method.

import numpy as np

number = 27

# Calculate the cube root using numpy.cbrt()
cube_root = np.cbrt(number)

print("Cube root of", number, "is:", cube_root)

Output

Cube root of 27 is: 3.0

That is it for this tutorial.

Related posts

Python sqrt

1 thought on “How to Find Cube Root in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.