Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Using Python 3.5 both at repl.it and the console in Windows, I get wrong answers for cube roots.

When the input is (-1)**(1/3), I get the complex number (0.5000000000000001+0.8660254037844386j) as the answer when it should simply be -1. Any negative value under this root seems to give a complex result.

Am I doing something wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

Exponentiation with negative bases typically involves complex numbers, so Python switches to complex numbers when it sees the negative base. Such exponentiation is typically mutlivalued, and Python doesn't always return the value you might expect.

For the special case of the 1/3 power with real bases, you could write a function like this:

def cubeRoot(x):
    if x >= 0:
        return x**(1/3)
    else:
        return -(-x)**(1/3)

Which will give the expected real cube root.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...