Skip to content Skip to sidebar Skip to footer

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.8660

Solution 1:

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.


Solution 2:

Actually, Python doesn't know that you are taking a cube root !

All it sees is a floating-point argument with a value close to 0.3333333333..., but due to the finiteness of the representation, it is impossible to guess that you mean exactly 1/3.

So all that Python can do is fall back on the usual definition of the exponentiation of negative bases to a real power (main branch), via the formula

(-x)^y = exp(y(ln(x) + iπ) = exp(y ln(x)) (cos(yπ) + i sin(yπ))

which yields a complex value.


Solution 3:

You get exactly this answer because the power operator computes

x**y = exp(y*ln(x))

and if x is not a positive real then its logarithm is computed from the main branch of the complex logarithm

ln(u+i*v)=0.5*ln(u²+v²) + i*arg(u+i*v)

where in math library terms arg(u+i*v)=atan2(v,u).

Thus ln(-1)=i*pi and

(-1)**(1.0/3)=exp(i*pi/3)=cos(pi/3)+i*sin(pi/3)

which has the value that you got. Floating point errors occur since y=1.0/3 is not exactly 1/3, pi is not exactly the mathematical constant of the same name and the trigonometric functions are also approximations to the exact mathematical functions.


Post a Comment for "Wrong Value For Cube Root In Python"