我正在编写一些SymPy代码来处理带有虚数的符号表达式。
首先,我想让它将x和y作为实数,并找到x = iy的解决方案。所以我可以这样做。
x, y = sympy.symbols("x y", real=True)
print(sympy.solve([x-sympy.I*y]))
(SymPy求得一个值列表,所有值必须为0.所以x-iy = 0 => x = iy)。 SymPy会正确告诉我
[{x: 0, y: 0}]
但是,如果我这样做(理论上相同):
x, y = sympy.symbols("x y")
print(sympy.solve([x-sympy.I*y, sympy.im(y), sympy.im(x)]))
然后现在SymPy告诉我
[{re(y): y, re(x): I*y, im(x): 0, x: I*y, im(y): 0}]
这在技术上是正确的,但并没有为我做任何事情。这只是SymPy中的一个限制,还是可以通过以这种方式约束复杂的x和y来让它给我x = y = 0?
答案 0 :(得分:2)
因为SymPy在简化实数对比复数时更好,所以以下策略有助于:为实部/虚部设置实变量,然后从它们形成复变量。
<Menu mnemonicParsing="false" text="File">
<MenuItem mnemonicParsing="false" onAction="#newFile" text="New">
<accelerator>
<KeyCodeCombination alt="UP" code="N" control="ANY" meta="UP" shift="UP" shortcut="UP"/>
</accelerator>
</MenuItem>
<MenuItem mnemonicParsing="false" onAction="#open" text="Open...">
<accelerator>
<KeyCodeCombination alt="UP" code="O" control="ANY" meta="UP" shift="UP" shortcut="UP"/>
</accelerator>
</MenuItem>
<MenuItem mnemonicParsing="false" onAction="#save" text="Save">
<accelerator>
<KeyCodeCombination alt="UP" code="S" control="ANY" meta="UP" shift="UP" shortcut="UP"/>
</accelerator>
</MenuItem>
<MenuItem mnemonicParsing="false" onAction="#saveAs" text="Save as...">
<accelerator>
<KeyCodeCombination alt="UP" code="S" control="ANY" meta="UP" shift="ANY" shortcut="UP"/>
</accelerator>
</MenuItem>
<SeparatorMenuItem mnemonicParsing="false"/>
<MenuItem mnemonicParsing="false" onAction="#quit" text="Quit">
<accelerator>
<KeyCodeCombination alt="UP" code="Q" control="ANY" meta="UP" shift="UP" shortcut="UP"/>
</accelerator>
</MenuItem>
</Menu>
现在x和y可以用作等式中的复变量,例如你的
from sympy import *
x1, x2, y1, y2 = symbols("x1 x2 y1 y2", real=True)
x = x1 + I*x2
y = y1 + I*y2
输出:sol = solve([x-I*y, im(y), im(x)])
print(x.subs(sol[0]), y.subs(sol[0]))
。
答案 1 :(得分:1)
以下是一个如何更一般地解决问题的示例。我使用了暗示使用实际的虚构角色会遇到麻烦,并使用collect_const()函数来执行缩减。
'''
Converts T to Pi Circuit Topology Symbolically
'''
from sympy import simplify, Symbol, pprint, collect_const
# Use this for your imaginary symbol
j = Symbol('j')
# Circuit symbols
R = Symbol('R')
w = Symbol('w')
L = Symbol('L')
C = Symbol('C')
# Arbitrary Circuit Element Equations
R1 = 1 / (j*w*C)
R2 = R + j*w*L
R3 = R + j*w*L
# Circuit conversion equations
RN = R1 * R2 + R2 * R3 + R1 * R3
RA = RN / R1
RB = RN / R2
RC = RN / R3
#Print the original circuit element equations
pprint(R1)
print("\n")
pprint(R2)
print("\n")
pprint(R3)
#Print the original solved equation, followed by the appropriately reduced equation
print("\nOriginal\t")
pprint(RA)
print("\nReduced\t")
pprint(collect_const(simplify(RA),j))
print("\nOriginal\t")
pprint(RB)
print("\nReduced\t")
pprint(collect_const(simplify(RB),j))
print("\nOriginal\t")
pprint(RC)
print("\nReduced\t")
pprint(collect_const(simplify(RC),j))