Search code examples
pythonsympysymbolic-mathpiecewise

How to update piecewise functions with sympy


I have a piecewise-defined function in the sense of the Piecewise class from sympy, and want to be able to manipulate the expressions and conditions within it to form new piecewise functions. For example, how could I change the expressions x**2 and -x in p below? Also I would like to be able to change the conditions.

I am trying to do this so that I don't have to type out explicit Piecewise definitions from scratch each time; most of the functions I am working with can easily be obtained from the other by simple mathematical operations. The only thing I can find that might work in ExprCondPair, but I don't understand how this works from looking at the official documentation on this. How can I manipulate the expressions and conditions in p below?

from sympy import Symbol, Piecewise
x = Symbol('x')
p = Piecewise((x**2, x<=0), (-x, True))

Solution

  • You can manipulate the expressions and conditions in a Piecewise function by accessing its args attribute, which is a tuple of (expr, cond) pairs.

    Here's a possible implementation:

    from sumpy import Symbol, Piecewise
    x = Symbol('x')
    p = Piecewise((x**2, x<=0), (-x, True))
    args = list(p.args)
    args[0] = (x**3, args[0][1])
    args[1] = (args[1][0], x > 0)
    p_new = Piecewise(*args)
    print(p_new)