SymPy和复数的平方根 [英] SymPy and square roots of complex numbers

查看:206
本文介绍了SymPy和复数的平方根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用solve计算二次方程式的根时,SymPy返回可以简化的表达式,但我无法简化它们.一个最小的示例如下所示:

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)

在这里,SymPy仅返回sqrt(-24-70*I),而Mathematica或Maple会以5-7*I等效.

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

我知道有两个平方根,但是这种行为需要例如SymPy从中返回相当复杂的解决方案

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)

同时,Maple和Mathematica都将愉快地给我提供两个可解决该方程的高斯整数.

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?

推荐答案

在逻辑上,找到z的平方根与求解方程(x + I * y)** 2 = z相同.因此,您可以这样做:

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

结果为[(-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

现在您可以使用my_sqrt(-24-70*I)并获取-5 + 7*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))

输出:[(-3, 3), (2, -4)]

这篇关于SymPy和复数的平方根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆