Search code examples
pythonspydersympy

How to factor exponential terms in Sympy Python?


How do I transform an expression like this:

y = [x*e^(x/2) + e^x + e^(x/2)]^2

in this:

y = {e^(x/2)*[x + e^(x/2) + 1]}^2

using Sympy??


Solution

  • It seems that the factoring doesn't recognize the exponential as well as a power. So convert the exp(x/2) -> y, factor, then back substitute:

    >>> eq
    (x*exp(x/2) + exp(x/2) + exp(x))**2
    >>> factor(eq.subs(exp(x/2),y)).subs(y,exp(x/2))
    (x + exp(x/2) + 1)**2*exp(x)