How to extract the cube root in Python

by Alex
How to extract the cube root in Python

The cube root of a number is a value that, when multiplied by a cube, yields the original number. In other words, the cube root is the value that, when multiplied by three times, gives us the number under the root. The cube root is denoted by the symbol “3√”. In the case of the square root, we have only used the symbol ‘√’ without specifying the degree, which is also called the radical. For example, the cube root of 125, denoted as 3√125, is 5 because multiplying 5 by itself three times yields 5 x 5 x 5 = 125 = 5^3.

The Cube Root in Python

To calculate the cube root in Python, use a simple mathematical expression x ** (1. / 3.), the result of which is the cube root of x as a floating point value. To check if the extraction operation is correct, round the result to the nearest whole number and take it to the third power, then compare whether the result is equal to x.
x = 8
cube_root = x ** (1./3.)
print(cube_root)
Output
2.0
In Python, we use the ** operator to raise a number to a power. Specifying a power of 1/3 in an expression with ** allows us to get the cube root of a given number.

Extracting the cube root from a negative number in Python

We cannot extract the cube root from negative numbers using the above method. For example, the cube root of the integer -64 should be -4, but Python returns 2+3.4641016157754j. To find the cube root of a negative number in Python, you first need to use the abs() function, and then you can use the simple expression with ** presented earlier to calculate it. Let's write a full function that checks to see if the input number is negative and then calculates its cube root accordingly.
def get_cube_root(x):
if x < 0:
x = abs(x)
cube_root = x**(1/3)*(-1)
else:
cube_root = x**(1/3)
return cube_root
print(round(get_cube_root(64))
print(get_cube_root(-64))
Output
4
-3.9999999999999996
As you can see, we need to round the result to get the integer value of the cube root.

Using the Numpy function cbrt()

The numpy library offers another way to find the cube root in Python, which is to use the cbrt() method. The np.cbrt() function calculates the cube root for each element of the array passed to it.
import numpy as np
cubes = [125, -64, 27, -8, 1]
cube_roots = np.cbrt(cubes)
print(cube_roots)
Output
[ 5. -4. 3. -2. 1.]
The np.cbrt() function is the simplest way to get the cube root of a number. It has no problem with negative input data and returns an integer number, e.g. -4 for the number -64 passed as argument, unlike the above approaches.

Related Posts

LEAVE A COMMENT