Sympy 从表达式中获取二次项和线性项

Sympy get quadratic and linear term from a expression

我在 x 的函数中有一个任意表达式 E,我想从这个表达式中得到二次项、线性项和常数项。我该怎么做?

import sympy
from sympy import sin, cos

def separate(expression, var):
    # ...
    return Q, L, C

x, a, b, c = sympy.symbols("x a b c")
separate(a*x**2 + b*x + c)   # Q = a, L = b, C = c

separate(cos(x), x)    # Q = 0, L = 0, C = cos(x)
separate(x*cos(x), x)  # Q = 0, L = cos(x), C = 0
separate(sin(x), x)    # Q = 0, L = 0, C = sin(x)
separate(x*sin(x), x)  # Q = 0, L = sin(x), C = 0

我试过使用导数,但是当我有像 cossinexp 等函数时,我的函数就崩溃了。

也许使用 .coeff()

def separate(expression, var):
    Q = expression.coeff(var**2)
    L = expression.coeff(var)
    C = (expression - (Q * var + L) * var).simplify()
    print(expression,' \t -->', [Q, L, C])
    return Q, L, C

结果:

a*x**2 + b*x + c     --> [a, b, c]
cos(x)       --> [0, 0, cos(x)]
x*cos(x)     --> [0, cos(x), 0]
sin(x)       --> [0, 0, sin(x)]