Search code examples
mathsympysimplifymathematical-expressionssimplification

Simplifying Sympy expressions as implicit functions of variables


I am wondering if there is any way to simplify Sympy expressions by rewriting the expression in terms of an already defined variable, making Python collect the terms fitting with that variable's definition.

Thanks in advance.


Solution

  • Something like this doesn't quite exist as you describe it, but it's not hard to do what you want.

    Firstly, there is the cse() function, which pulls out common subexpressions as variables automatically. However, it will not use pre-defined variables if that is what you want. But if your goal is just to simplify the evaluation of an expression, and you don't really care what the intermediate expressions are, cse is your best bet.

    One trick that you can use is to isolate a single part your subexpressions and substitute them. For example, say you had an expression expr containing x + y, and you wanted to replace x + y with z. Simply doing expr.subs(x + y, z) often works. But in some cases it won't because subs only replaces x + y if it finds it exactly in the expression.

    A trick you can use instead is to "solve" (you can do it automatically with solve if you like) the substitution z = x + y for a single variable, like x = y - z, and replace that (expr.subs(x, y - z)). Since there is no ambiguity on where x appears like there was for x + y, this will replace it everywhere. You often then must expand the expression to get things to cancel out.