问题
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?
回答1:
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.
回答2:
I can answer why this is happening, but not why the behavior was chosen.
a/(a - 1)
evaluates to 0.2/-0.8 which is -0.25, which is converted to a complex number by cmath.sqrt
, while
b/(b - 1)
evaluates to (0.2+0j)/(-0.8+0j) which is (-0.25-0j), which is converted to a complex number with a negative complex component.
For a simpler example,
cmath.sqrt(0j) == 0j
cmath.sqrt(-0j) == -0j
来源:https://stackoverflow.com/questions/36584466/square-root-of-complex-numbers-in-python