prevent Sympy from simplifying expression python after a substitution

Question:

I’m using Sympy to substiture a set of expressions for another using the Subs function, and I would like for the program not to rearrage or simplify the equations.
i.e if i were substituting x+y for a in

a+b+c+a to return x+y+b+c+x+y

Does anyone know of a way to perform this?

Many thanks

Asked By: user124123

||

Answers:

The only way to do it is to do Add(x, y, b, c, x, y, evaluate=False), which unfortunately isn’t very easy to work with.

Answered By: asmeurer

You can use list/tuple unpacking to automate this as well

lst = (1,4,5,6, nsimplify(1/2))
lstadd = Add(*lst, evaluate=False)
display(lstadd)
display(nsimplify(lstadd))
display(lstadd.evalf())

enter image description here

Answered By: Dara O h

I have found a better way of going about this rather than using classes like Add. What if you have an expression that has a lot of operations? Using these classes would be cumbersome.

Instead, we can use the evaluate function, which is used inside of a context manager. Here is an example of an expression that has quite a few operations, but we can substitute without the expression immediately simplifying/evaluating.

import sympy as sp

x, y = sp.symbols('x y')
expr = x**2*sp.sqrt(y**2 + 45*x)
print(expr)

# Substitute without evaluating
with sp.evaluate(False):
    expr_subs = expr.subs([(x, 2), (y, 7)])
    print(expr_subs)
print(expr_subs.doit())

This will output what is desired:

x**2*sqrt(45*x + y**2)
2**2*sqrt(7**2 + 45*2)
4*sqrt(139)

Notice that any substitution that occurs inside the context manager will not evaluate, but it will if it is outside. Use the doit() method to evaluate/simplify the expression, but it will raise an error if doit() is called inside the context manager. Note that the documentation for this function (located in the parameters.py) warns us that this functionality is experimental.

Your Case


For your specific case,

import sympy as sp

x, y, a, b, c = sp.symbols('x y a b c')

with sp.evaluate(False):
    expr = a + b + c + a
    expr_sub = expr.subs(a, x + y)
print(expr_sub)

Output:

c + b + x + y + x + y
Answered By: Gabe Morris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.