Search code examples
pythonsympy

sympy: how to factor expressions inside parentheses only


I want to simplify the following expression using sympy:

-8*F_p + 8*Omega*u + 6*alpha*u*(u**2 + v**2) - 5*beta*u*(u**4 + 2*u**2*v**2 + v**4) - 8*gamma*omega*v

So it ends up like

-8*F_p + 8*Omega*u + 6*alpha*u*r**2 - 5*beta*u*r**4 - 8*gamma*omega*v

with r**2=u**2+v**2

It is not working though, but when I use

factor(u**4 + 2*u**2*v**2 + v**4).subs(u**2+v**2, r**2)

The output I get is r**4 as expected. Unfortunately, I don't get this simplification when I try this with the first expression. I wonder if there is a way to tell sympy to factor only the expressions inside the innermost parentheses.

Here is the full code

from sympy import symbols

u, v, r = symbols('u v r')
# parameters
alpha = symbols('alpha', positive=True)
beta = symbols('beta', positive=True)
F_p = symbols('F_p', positive=True)
gamma = symbols('gamma', positive=True)
omega = symbols('omega', positive=True)
Omega = symbols('Omega', positive=True)
f=-8*F_p + 8*Omega*u + 6*alpha*u**3 + 6*alpha*u*v*v - 5*beta*u**5 - 10*beta*u**3*v**2 - 5*beta*u*v**4 - 8*gamma*omega*v
print(f)
f = collect(f, [alpha, beta])
print(simplify(f))
# Substitute u^2 + v^2 = r^2
subs_dict = {u**2 + v**2: r**2}

# Simplify the expression
simplified_expr = simplify(f.subs(subs_dict))
print(simplified_expr)
print(factor(u**4 + 2*u**2*v**2 + v**4).subs(u**2+v**2, r**2))

Solution

  • Sometimes the easiest thing to do is to re-arrange the expression you are trying to replace:

    >>> f.subs(v**2, r**2 - u**2).expand()
    -8*F_p + 8*Omega*u + 6*alpha*r**2*u - 5*beta*r**4*u - 8*gamma*omega*v
    

    For an older version of SymPy, that doesn't replace the v**2 in the way you want, you might have to fall back to using v, instead and then cleaning up residual v-expressions.

    >>> s=sqrt(var('r',positive=True)**2-u**2)
    >>> f.subs(v,s).expand().subs(s,v)
    -8*F_p + 8*Omega*u + 6*alpha*r**2*u - 5*beta*r**4*u - 8*gamma*omega*v