I have run across some confusing behaviour with square roots of complex numbers in python. Running this code:
from cmath import sqrt
a = 0.2
b = 0.2 + 0j
print(sqrt(a / (a - 1)))
print(sqrt(b / (b - 1)))
gives the output
0.5j
-0.5j
A similar thing happens with
print(sqrt(-1 * b))
print(sqrt(-b))
It appears these pairs of statements should give the same answer?
Both answers (+0.5j
and -0.5j
) are correct, since they are complex conjugates -- i.e. the real part is identical, and the imaginary part is sign-flipped.
Looking at the code makes the behavior clear - the imaginary part of the result always has the same sign as the imaginary part of the input, as seen in lines 790 and 793:
r.imag = copysign(d, z.imag);
Since a/(a-1)
is 0.25
which is implicitly 0.25+0j
you get a positive result; b/(b-1)
produces 0.25-0j
(for some reason; not sure why it doesn't result in 0.25+0j
tbh) so your result is similarly negative.
EDIT: This question has some useful discussion on the same issue.