Search code examples
pythoncomplex-numbersexponent

Python exponent operator and complex numbers


Why does python does print(type(-1**0.5)) return float instead of complex?

Getting the square root of negative integer of float always mathematically consider as complex numbers. How does python exponent operator support to get complex number?

print(type(-1**0.5))
 <type 'float'>    

Solution

  • In the mathematical order of operations, exponentation comes before multiplication and unary minus counts as multiplication (by -1). So your expression is the same as -(1**0.5), which doesn't involve any imaginary numbers.

    If you do (-1)**0.5 you'll get an error in Python 2 because the answer isn't a real number. If you want a complex answer, you need to use a complex input by doing (-1+0j)**0.5. (In Python 3, (-1)**0.5 will return a complex result.)