pythonsympysymbolic-mathpiecewise

Piecewise functions with sympy: how to define function only for certain input values?


I'm experimenting with Piecewise functions with sympy, and have found that it doesn't like it when I give pairs of expressions and conditions only for certain intervals. For example, when I type the following, when attempting to make the function undefined, for x<0:

from sympy import Symbol, Piecewise
x = Symbol('x')
p = Piecewise((3, 0<=x<=5), (5, x>5))

I get the error message

TypeError: cannot determine truth value of Relational

Yet it works fine when I remove the 0<= from the first condition, but assigns the corresponding expression 3 for negative x, which I don't want. In many contexts it makes no sense for a function to be defined for negative x, and I would like to reflect this in my code.


Solution

  • You can define a piecewise function for certain intervals by using And function to combine conditions:

    from sympy import Symbol, Piecewise, And
    x = Symbol('x')
    p = Piecewise((3, And(0<=x, x<=5)), (5, x>5))
    

    Here I ensured that the function is defined only for 0 <= x <= 5. For x > 5 the function returns 5 and for x < 0, the function is undefined.