Search code examples
pythonpython-3.xintoperator-overloadingcomplex-numbers

Basic operations returning complex number


I have written this short and hopefully pretty explanatory code as I encountered an interesting unexpected behaviour while dealing with basic math operations.

from collections import namedtuple

P = namedtuple('P', 'x y')

# euclidean distance with missing parentheses before sqroot
dist = lambda p1, p2:(p1.x-p2.x)**2 + (p1.y-p2.y)**2 ** 0.5
# correct_dist = lambda p1, p2: ((p1.x-p2.x)**2 + (p1.y-p2.y)**2)**0.5

A = P(0, 0)
B = P(1, 1)
AB = dist(A, B)

print(AB, type(AB))  # returns complex?!
print(-1**2 -1**2 **0.5)  # -2.0 (as expected since root not applied to the sum)

By the way, this is more for understanding purposes (not for actual use).
Help me understand this better please!


Solution

  • you get a complex number because you have a negative number -1 raised to an irrational number (2**0.5), you have in your dist function:

    (-1)**(2**0.5)
    

    you can read more about raising negative numbers to fractional or irrational numbers here: