piecewise( [ [ ( begin
, end
) , function
] , ... ] , var=variable )
A piecewise function in SageMath defined in part by function
on the domain from begin
to end
. Consecutive domains should share an endpoint to avoid unexpected errors. The optional var
keyword argument specifies which single symbolic variable is the argument of the complete function.
The argument function
for each domain must be the name of a symbolic function, not a numeric function. Symbolic functions are constructed from numeric functions using function. Symbolic functions entail significant overhead that can make piecewise
unsuitable for purely numeric calculations.
The current version of SageMath makes a distinction for this function between open and closed domains. Open domains are specified with parentheses ( )
. Closed domains are specified with square brackets [ ]
. Attempting to specify a mixed domain ( ]
or [ )
leads to Python syntax errors.
To ensure a piecewise function consisting of several domains is valid at all points in the complete domain, alternately specify successive domains as open and closed. If the domains are all open then points on the boundaries will not be included, and making all domains closed leads to the error message domains must be pairwise disjoint
.
Specifying a partial domain when plotting a piecewise function is supported in the current version of SageMath. Previously this led to the opaque error message local variable 'G' referenced before assignment
.
Including a numeric Python-callable function directly in piecewise
leads to the error message unable to simplify to float approximation
. This is avoided by constructing a symbolic function using function.
Examples:
f = piecewise( [ [(0,1),x], [[1,3],2-x], [(3,4),x-4] ] ) show( plot( f, 0, 4, figsize=[4.5,2], color=(0,.5,1) ) )
f = piecewise( [ [(0,1),lambda x:-.6], [[1,2],lambda x:-.2], [(2,3),lambda x:.2], [[3,4],lambda x:.6] ] ) show( plot( f, 0, 4, figsize=[4.5,2], color=(0,.5,1) ) )
Related functions: function
Function category: basic functions sagemath-docs