How to write a piecewise-defined function (in Python, using SymPy)
Task
In mathematics, we use the following notation for a “piecewise-defined” function.
This means that for all
How can we express this in mathematical software?
Solution
This answer assumes you have imported SymPy as follows.
1
2
from sympy import * # load all math functions
init_printing( use_latex='mathjax' ) # use pretty math output
SymPy has support for piecewise functions built in, using Piecewise
.
The function above would be written as follows.
1
2
3
var( 'x' )
formula = Piecewise( (x**2, x>2), (1+x, x<=2) )
formula
We can test to be sure the function works correctly by plugging in a few
1
formula.subs(x,1), formula.subs(x,2), formula.subs(x,3)
For
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)