To find the cube root of a negative number in Python, you can use the cbrt()
function from the numpy
module or the pow()
function from the math
module or the **
operator.
Here’s an example of how to use the cbrt()
function from the numpy
module to find the cube root of a negative number in Python:
import numpy as np
def cube_root(x):
return np.cbrt(x)
print(cube_root(-8)) # Output: (-2.0+0j)
print(cube_root(-27)) # Output: (-3.0+0j)
print(cube_root(-64)) # Output: (-4.0+0j)
pow() function to find the cube root of a negative number in Python
Here’s an example of how to use the pow()
function to find the cube root of a negative number in Python:
import math
def cube_root(x):
return pow(x, 1/3)
print(cube_root(-8)) # Output: (-2+0j)
print(cube_root(-27)) # Output: (-3+0j)
print(cube_root(-64)) # Output: (-4+0j)
** operator to find the cube root of a negative number in Python
you can also use the **
operator to find the cube root of a negative number in Python. Here’s an example:
def cube_root(x):
return x ** (1/3)
print(cube_root(-8)) # Output: -2.0
print(cube_root(-27)) # Output: -3.0
print(cube_root(-64)) # Output: -4.0
Cube root of a negative number returns a complex number
Yes, that’s correct. When you try to find the cube root of a negative number in Python, the result is a complex number. This is because a negative number does not have a real cube root, as the cube of a real number is always positive.
For example, when you try to find the cube root of -8 using the cbrt()
function from the numpy
module, the result is (-2+0j), which is a complex number with a real part of -2 and an imaginary part of 0.
Similarly, when you try to find the cube root of -27 using the pow()
function from the math
module or the **
operator, the result is (-3+0j), which is a complex number with a real part of -3 and an imaginary part of 0.
To get the real part of the result as a real number, you can use the real
attribute of the result. For example:
import numpy as np
def cube_root(x):
return np.cbrt(x).real
print(cube_root(-8)) # Output: -2.0
print(cube_root(-27)) # Output: -3.0
print(cube_root(-64)) # Output: -4.0
import math
def cube_root(x):
return pow(x, 1/3).real
print(cube_root(-8)) # Output: -2.0
print(cube_root(-27)) # Output: -3.0
print(cube_root(-64)) # Output: -4.0