我正在尝试替换子表达式。关于这个主题有很多问题,但我发现使用通配符变量作为乘数似乎可以单独工作,但在存在额外术语时则不然。例如:
import sympy as smp
x, y, z, a = smp.symbols("x y z a")
b = smp.Wild("b")
expr_1 = x/a**2 + y/a**2 + z/a**2
replacement = b*x + b*y + b*z
replaced = expr_1.replace(replacement, b) # essentially, I am saying that x + y + z = 1
该示例有效,结果是
1/a**2
。但如果我添加额外的零件,替换就不起作用了。
expr_2 = expr_1 + 20/a
not_replaced = expr_2.replace(replacement, b)
结果
not_replaced
与expr_2
相同。
这种行为是预期的吗?有没有办法像我尝试过的那样使用
.replace
和通配符变量来实现所需的结果?
尝试代数替换:
x+y+z=1
)或
rel = Eq(x+y+z,1);
eq = expr_2 + x
rep=solve(rel, (eq.free_symbols & rel.free_symbols), dict=True)[0]
new=eq.subs(rep).expand()
per=solve(rel, new.free_symbols & rel.free_symbols, dict=True)[0]
new.subs(per).expand()
给予
x + 20/a + a**(-2)