Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

math - Wrong value for cube root in Python

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...