SymPy and square roots of complex numbers

╄→гoц情女王★ 提交于 2020-01-02 04:07:06

问题


When using solve to compute the roots of a quadratic equation, SymPy returns expressions which could be simplified but I can't get it to simplify them. A minimal example looks like so:

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

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

I'm aware that there are two square roots, but this behavior entails that SymPy will, for example, return pretty complicated solutions from

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

while, again, Maple and Mathematica will both happily give me the two Gaussian integers that solve this equation.

Is there an option or something that I'm missing?


回答1:


Finding the square root of z is logically the same as solving 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))

The result is [(-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 example with a quadratic equation:

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)]




回答2:


If you have the mpmath package, 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 do the conversion back to a sympy object.

Update

As pointed out in the comments, this performs numeric evaluation, not symbolic. That is, the above is not really superior to this:

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

The above have two interesting aspects. First, the cmath module is part of the standard library. Secondly, since result is given in terms of integers, we are guaranteed that result is actually the exact symbolic value (and it can easily be converted to a sympy object). If the solution is non-integer, the result is expressed as floats. This is of course not a general good solution to the problem of symbolic complex square roots, but it is useful if you know beforehand that the solution is integer.



来源:https://stackoverflow.com/questions/41324497/sympy-and-square-roots-of-complex-numbers

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