子表达式的替代(标量)倍数

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

我需要从表达式中识别和替换子表达式的multiple

x**2 - 3x + 6exp(x) 中消除 1x - 3exp(x) 得到 x**2 - xx**2 - 3exp(x).

我还没有找到一种优雅而正确的方式来面对这个问题。 在我的几次尝试中,我尝试了

extract_additively
的递归应用,但它不是通用的并且可能会失败!

“消除”一个表达式的倍数的正确方法是什么?

import sympy as sp
import IPython.display as disp


x = sp.Symbol('x')

yp = x**2 - 3*x + 6*sp.exp(x)

# testing sub-expressions
yhs = [1*x - 3*sp.exp(x), # OK
       5*x - 3*sp.exp(x), # FAIL: coefficient greater than the original
       - 7*sp.exp(x),   #   FAIL: coefficient greater than the original
       ]

# recursive extraction
for yh in yhs:
    yp_mod = yp.expand()

    while yp_mod.extract_additively(yh):
        yp_mod = yp_mod.extract_additively(yh)
    while yp_mod.extract_additively(-yh): # test for opposite sign
        yp_mod = yp_mod.extract_additively(-yh)

    disp(yp_mod)

#x**2 - x
#x**2 - 3*x + 6*exp(x)
#x**2 - 3*x + 6*exp(x)
python sympy substitution
© www.soinside.com 2019 - 2024. All rights reserved.