Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong value for cube root in Python

Tags:

python

math

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?

like image 351
Lupilum Avatar asked Nov 16 '25 02:11

Lupilum


1 Answers

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.