Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to tell sympy to simplify or change between minimums and absolute values?

For example, how can we make this simplify to zero (or show me where I’ve made a dumb mistake and then it just works)

import sympy
sympy.var('s t', real=True)
(s - 2 * sympy.Min(s, t) - sympy.Abs(s - t)).simplify()  # should be zero?

I see evidence that sympy knows about these kind of relations but I’m not clear what triggers it to go from $|t – s|$ to a representation involving min or max.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use rewrite(Piecewise):

In [239]: e
Out[239]: s - │s - t│ - 2⋅Min(s, t)

In [240]: e.rewrite(sympy.Piecewise)
Out[240]: 
      ⎛⎧s  for s ≤ t⎞   ⎛⎧s - t   for s - t ≥ 0⎞
s - 2⋅⎜⎨            ⎟ - ⎜⎨                     ⎟
      ⎝⎩t  otherwise⎠   ⎝⎩-s + t    otherwise  ⎠

In [241]: e.rewrite(Piecewise).simplify()
Out[241]: -t
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading