Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square root of complex numbers in python

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?

like image 575
CleptoMarcus Avatar asked Apr 12 '16 21:04

CleptoMarcus


People also ask

How do you square root a complex number?

The square root of a complex number can be determined using a formula. Just like the square root of a natural number comes in pairs (Square root of x2 is x and -x), the square root of complex number a + ib is given by √(a + ib) = ±(x + iy), where x and y are real numbers.

How do you square root a number in Python?

The math. sqrt() method returns the square root of a number.

Is the square root of a complex number Complex?

Let's consider the complex number 21-20i. We know that all square roots of this number will satisfy the equation 21-20i=x2 by definition of a square root. We also know that x can be expressed as a+bi (where a and b are real) since the square roots of a complex number are always complex.


1 Answers

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.

like image 75
tzaman Avatar answered Sep 23 '22 23:09

tzaman