SymPy 虚数 [英] SymPy Imaginary Number
问题描述
我正在忙着编写一些 SymPy 代码来处理带有虚数的符号表达式.
I'm messing around with writing some SymPy code to handle symbolic expressions with imaginary numbers.
首先,我想让它把 x 和 y 作为实数,然后找到 x=iy 的解.所以我可以这样做.
To start out, I want to get it to take x and y as real numbers and find the solution where x=iy. So I can do this as follows.
x, y = sympy.symbols("x y", real=True)
print(sympy.solve([x-sympy.I*y]))
(SymPy 求解需要一个值列表,所有这些值都必须为 0.所以 x-iy=0 => x=iy).SymPy 会正确地告诉我
(SymPy solve takes a list of values, all of which must be 0. So x-iy=0 => x=iy). SymPy will correctly tell me
[{x: 0, y: 0}]
但是,如果我以(理论上相同的)方式执行此操作:
However, if I do this a (theoretically identical) way:
x, y = sympy.symbols("x y")
print(sympy.solve([x-sympy.I*y, sympy.im(y), sympy.im(x)]))
那么现在SymPy告诉我
Then now SymPy tells me
[{re(y): y, re(x): I*y, im(x): 0, x: I*y, im(y): 0}]
这在技术上是正确的,但并没有为我完成所有事情.这只是 SymPy 中的一个限制,还是我可以通过以这种方式约束复数 x 和 y 来给我 x=y=0?
And this is technically correct, but hasn't done everything for me. Is this just a limitation in SymPy, or can I get it to give me x=y=0 by constraining complex x and y in this way?
推荐答案
因为 SymPy 比复数更擅长简化实数对,以下策略有帮助:为实部/虚部设置实变量,然后形成复变量来自他们.
Because SymPy is better at simplifying pairs of real numbers than complex numbers, the following strategy helps: set up real variables for real/imaginary parts, then form complex variables from them.
from sympy import *
x1, x2, y1, y2 = symbols("x1 x2 y1 y2", real=True)
x = x1 + I*x2
y = y1 + I*y2
现在 x 和 y 可以用作像您这样的方程中的复变量
Now x and y can be used as complex variables in an equation such as yours
sol = solve([x-I*y, im(y), im(x)])
print(x.subs(sol[0]), y.subs(sol[0]))
输出:0 0
.
这篇关于SymPy 虚数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!