Square root of complex numbers in python

末鹿安然 提交于 2019-12-04 23:39:15
tzaman

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!