I can't find the coefficient of a variable when a dominator is in expression

billy :

I have been trying to find the coefficients of some lengthy expressions, and even though they are non zero, the result I take is equal to 0.

I think the problem is that I don't get the result to be (s1+s2)/s4 on this mwe:

Sym1,Sym2,Sym3,Sym4 = sy.symbols('s1, s2, s3, s4')
xx                  = sy.Symbol('x')
TestExp             = Sym1*xx + Sym2*xx + Sym3
print(TestExp.coeff(xx))
TestExp2            = (Sym1*xx + Sym2*xx + Sym3)/Sym4
print(TestExp2.coeff(xx))
smichr :

coeff is pretty literal so if there is no term with xx as a factor then it will return 0. As your expression is, it appears as a fraction, a single term, and there is no factor of xx in that term. (But there is in the numerator.) Try expanding your expression first:

>>> print(TestExp2.expand().coeff(xx))
s1/s4 + s2/s4

And touch it with factor_terms or collect to simplify:

>>> factor_terms(_)
(s1 + s2)/s4

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=405592&siteId=1