Piecewise Functions in Python’s sympy
In many applications, we are faced with functions that are defined piecewise. For instance, consider the function
sympy
offers an easy and intuitive way to work with functions like that: the
Piecewise
class. For each case in the piecewise function, we define a pair (2-tuple) with the function on the subdomain (e.g. 3−𝑥²) and a condition specifying the subdomain (e.g. |𝑥|<1). For the example above, we would write
We can easily plot piecewise functions using
plot_piecewise
from the sympy plotting backends
spb
:
Note that
plot_piecewise
not only marks the transition points between two cases but also discontinuities (if present) are displayed nicely.
We can work on piecewise-defined functions like normal functions. For example, we differentiate them:
We can expand them in a power series, which keeps the piecewise structure:
Or we can integrate them. For a definite integral, we just say
For an indefinite integral, we can use
and each case is handled separately.
Often, we don’t define piecewise functions ourselves, but they are output of some operation. Then we often want to get access to the different parts of the function. This can be obtained by the method
as_expr_set_pairs
:
Evaluating piecewise function work just like normal expressions, using
subs
. It behaves as one would intuitively expect. Substituting 𝑥=0 just returns the single function value for the subdomain in which 𝑥=0 lies:
However, if you substitute 𝑥 for another symbol, say 𝑦, we retain the piecewise function structure:
Finally, what if you want to multiply a piecewise function by some expression? The intuitive approach doesn’t work:
Use the function
piecewise_fold
instead! Here, we get
That covers the typical use cases of piecewise functions. Have fun playing!