Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sympy: how to simplify across multiple expressions

Tags:

python

sympy

I have a set of sympy expressions like this (a few hundred of them):

>>> foo = parse_expr('X | Y')
>>> bar = parse_expr('(Z & X) | (Z & Y)')
>>> baz = parse_expt('AAA & BBB') # not needed for this example; just filler

I can simplify one in isolation:

>>> simplify(bar)
Z & (X | Y)

Is there a way to simplify, including the whole set of variables available?

>>> mysimplify(bar, include=(foo,bar,baz))
Z & foo
like image 317
ajwood Avatar asked Feb 01 '19 02:02

ajwood


People also ask

How do you simplify equations in Python?

simplify() method, we can simplify any mathematical expression. Parameters: expression – It is the mathematical expression which needs to be simplified. Returns: Returns a simplified mathematical expression corresponding to the input expression.

How do you simplify trigonometric expressions in Python?

To simplify expressions using trigonometric identities, use trigsimp() . trigsimp() also works with hyperbolic trig functions.

How do you use expand in SymPy?

With the help of sympy. expand() method, we can expand the mathematical expressions in the form of variables by using sympy. expand() method. Return : Return mathematical expression.


1 Answers

You can take advantage of Common Subexpresion Elimination. You must use it in combination with simplify by combining all your expressions into a single artificial expression (for example, by passing them as arguments to a fictitious function). I don't think that it will always work as desired, however on a loose analogue of your example it produces the expected result:

In [1]: from sympy import *

In [2]: myexprlist = sympify('listofexpr(x|y, (z&x)|(z&y))')

In [3]: cse(simplify(myexprlist))
Out[3]: ([(x0, Or(x, y))], [listofexpr(x0, And(x0, z))])

The first entry in the result is a list of introduced subexpressions. In this case the subexpression x|y has been denoted with x0. The second part of the result is the simplified expression (packaged into a list, since the input can be a list of expressions).

like image 60
Leon Avatar answered Sep 30 '22 14:09

Leon