Search code examples
pythonsympysymbolic-math

Simplify in sympy with custom symbols


Suppose that I have sympy variables x, y and z

I have the expression (x + y) (x + y) + x

Is it possible that I am able to define z as x + y so that I can "simplify" the expression above to z^2 + x?

That is, I want to use z wherever I can in the simplified expression.


Solution

  • Yes, use subs as in

    >>> var('x:z')
    (x, y, z)
    >>> ((x + y)*(x + y) + x).subs(x+y,z)
    x + z**2
    

    The subs routine will sometimes try to be smart about substitutions, but works best when the substitution target is a symbol (and hence unambiguous). So if you want to try the replacement x+y->z in a more ambiguous expression, try replacing x->z-y, simplify, and then resubstitute z-y->x to restore anything that didn't change:

    >>> ((x*x + 2 * x * y + y * y) + x).subs(x,z-y).expand().subs(z-y,x)
    x + z**2