SymPy and the square roots of complex numbers

When using solve to calculate the roots of a quadratic equation, SymPy returns expressions that can be simplified, but I cannot simplify them. A minimal example looks like this:

 from sympy import * sqrt(-24-70*I) 

Here, SymPy simply returns sqrt(-24-70*I) , while Mathematica or Maple will respond with the equivalent of 5-7*I

I know that there are two square roots, but this leads to the fact that SymPy, for example, will return rather complex solutions from

 z = symbols("z") solve(z ** 2 + (1 + I) * z + (6 + 18 * I), z) 

while Maple and Mathematica will both joyfully give me two Gaussian integers that solve this equation.

Is there an option or something that I am missing?

+5
source share
2 answers

The search for the square root of z coincides logically with the solution of the equation (x + i * y) ** 2 = z. So you can do just that:

 from sympy import * z = -24-70*I x, y = symbols('x y', real=True) result = solve((x+I*y)**2 - z, (x, y)) 

Result [(-5, 7), (5, -7)]

For convenience, this can be wrapped as a function:

 def my_sqrt(z): x, y = symbols('x y', real=True) sol = solve((x+I*y)**2 - z, (x, y)) return sol[0][0] + sol[0][1]*I 

Now you can use my_sqrt(-24-70*I) and get -5 + 7*I


The same strategy helps in your quadratic equation example:

 x, y = symbols('x y', real=True) z = x + I*y solve(z ** 2 + (1 + I) * z + (6 + 18 * I), (x, y)) 

Output: [(-3, 3), (2, -4)]

+3
source

If you have mpmath you can do something like

 from sympy import * import mpmath a = -24-70*I b = mpmath.mpc(re(a), im(a)) # a as mpmath.mpc object c = mpmath.sqrt(b) d = simplify(c) # Convert back to sympy object print(d) # 5.0 - 7.0*I 

Note that there may be a cheaper way (than simplify ) to convert back to a sympy object.

Update

As stated in the comments, this performs a numerical evaluation, not a symbolic one. That is, the above does not far exceed this:

 import cmath result = cmath.sqrt(-24 - 70j) print(result) # 5 - 7j 

The foregoing has two interesting aspects. First, the cmath module is part of the standard library. Secondly, since result is specified in terms of integers, we guarantee that result is actually an exact symbolic value (and it can easily be converted to a sympy object). If the solution is not integer, result is expressed as a float. This, of course, is not an overall good solution to the problem of symbolic complex square roots, but it is useful if you know in advance that the solution is a whole.

0
source

Source: https://habr.com/ru/post/1261882/


All Articles