ID : 372

viewed : 127

Tags : PythonPython Math

96

This tutorial will explain different methods to get a cube of an integer or a float variable in Python. To get a cube root of a number in Python, we first need to know about how to get the exponent of a number and what operator is used to get the exponent of a number in Python. We will also see how to handle the negative numbers while calculating its cube root and what operator or method to use to get the cube root of a number in Python.

`**`

We can use `**`

symbol in Python to calculate an exponent of the number; it is also called the power operator. To calculate the cube root, we can set the power equal to `1/3`

.

We should keep in mind that for some reason, the cube root of the negative numbers is not calculated correctly by this method. For example, the cube root of integer `-27`

should be `-3`

but Python returns `1.5000000000000004+2.598076211353316j`

. This problem can easily be handled by ignoring the integer’s negative sign before calculating its cube root.

The below code example demonstrates how to calculate the cube root of positive as well as negative numbers in Python:

`def get_cuberoot(x): if x < 0: x = abs(x) cube_root = x**(1/3)*(-1) else: cube_root = x**(1/3) return cube_root print(get_cuberoot(64)) print(get_cuberoot(-64)) print(round(get_cuberoot(-64))) `

Output:

`3.9999999999999996 -3.9999999999999996 -4 `

Note

As we can see in the above example, we may need to round the result to get the cube root’s exact value.

`pow()`

FunctionThe `pow()`

function takes a number (can be integer or float) as the first argument and the exponent or power of the number as the second argument and returns the provided number’s power.

We can pass the `1/3`

as the second argument to calculate the desired number’s cube root. The `pow()`

function also returns the wrong answer for the negative numbers’ cube root; hence negative numbers should be handled separately.

The below code example demonstrates how to calculate the cube root of a number using the `pow`

method:

`def get_cuberoot(x): if x < 0: x = abs(x) cube_root = pow(x,1/3)*(-1) else: cube_root = pow(x,1/3) return cube_root print(get_cuberoot(64)) print(get_cuberoot(-64)) print(round(get_cuberoot(-64))) `

Output:

`3.9999999999999996 -3.9999999999999996 -4 `

`cbrt()`

Function of the NumPy LibraryThe `cbrt()`

function of the NumPy library is the easiest method to calculate a number’s cube root. It does not get in trouble with negative inputs and returns the exact number like 4 for input 64, unlike the methods discussed above.

The problem with this method is that it is not a built-in function of Python and the NumPy library needs to be installed to use the `cbrt()`

function.

The below example code demonstrates how to use the `cbrt`

function to get the cube root of a number in Python:

`import numpy as np print(np.cbrt(64)) print(np.cbrt(-64)) print(np.cbrt(9.4)) `

Output:

`4.0 -4.0 2.11045429449015 `