用通配符变量替换表达式只能单独工作

问题描述 投票:0回答:1

我正在尝试替换子表达式。关于这个主题有很多问题,但我发现使用通配符变量作为乘数似乎可以单独工作,但在存在额外术语时则不然。例如:

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
和通配符变量来实现所需的结果?

python sympy
1个回答
0
投票

尝试代数替换:

  1. 求解变量 `x=1-y-z' 的所需关系 (
    x+y+z=1
    )
  2. 进行替换
  3. 解决完成后仍然存在的任何变量(如果有)的关系,并解决 that 变量
  4. 所需的关系
  5. 进行最后的替换

enter image description here

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)
© www.soinside.com 2019 - 2024. All rights reserved.