Search code examples
mathsympy

Trying to combine like terms in Sympy


Code

Am tring to combine the gamma terms above together (so that the final expression reads gamma**(alpha/(alpha-1))*(4alpha+1)+r, but have been unable to do so so far. I assumed all variables were real and positive when introducing them in Sympy.

I tried to use both sympy.simplify and sympy.collect. Both methods work when there is no alpha-1 in the denominator, so I suspect this has something to do with the expression being undefined for alpha=1, but have unable to find out how to tell Sympy to ignore this. Sympy.factor works when there is no + r term, but it does not work in this case. Any help would be appreciated! (the actual expression I'm evaluating has many more terms and I would much prefer to not have to combine them by hand if I can avoid it.


Solution

  • You can make your own function to factor parts of an expression that depend on certain variables:

    ft = lambda eq, *v: factor_terms(t:=eq.as_independent(*v,as_Add=True))[1]+t[0]
    >>> ft(hi, gamma)
    gamma**(alpha/(alpha - 1))*(4*alpha + 1) + r
    

    Or you can get the exact expression upon which you want to collect

    >>> list(hi.atoms(Pow))
    [1/(alpha - 1), gamma**(alpha/(alpha - 1))]
    >>> collect(hi, _[1])
    gamma**(alpha/(alpha - 1))*(4*alpha + 1) + r