Search code examples
pythonmathcomplex-numbersnth-root

How can I prevent the result from being a complex number? (Cube root of -27)


I've figured out the following solution (probably not that hard anyway):

n1, n2 = -27, 3
root = ( n1 ** (1/n2))
print(root)

(1.5000000000000004+2.598076211353316j)

Unless I'm making a very dumb mistake, it should print -3 instead.


Solution

  • To find the real cubic root of a negative number, use:

    number = -27
    if number > 0:
        real_root = number ** (1/3)
    elif number < 0:
        real_root = - (abs(number) ** (1/3))
    elif number == 0:
        real_root = 0