Advice: Singularities in piecewise functions
With few exceptions, Maple evaluates the arguments to a function before the function itself is called. In particular, this happens for the piecewise function. Thus, even though the result is only the first case corresponding to a true condition, all the cases will be evaluated.
One situation where this behaviour can cause errors is when one of the cases has a singularity. For example:
> f:= x -> piecewise(x < 1, 1, 1/x):
> f(0);
Error, (in f) division by zero
At
the condition
is true, so
f(0)
might be expected to evaluate to 1. However, the
1/x
is still evaluated with
x
replaced by
0
, and this produces the error. One way to work around the problem is to use
traperror
to intercept the error.
> f:= x -> piecewise(x < 1, 1, traperror(1/x)):
> f(0);
This may not be a completely satisfactory solution, however. It is still not possible to evaluate
f(x)
and then substitute
x=0
, because
f(x)
evaluates to
(the
1/x
evaluates without an error, and so
traperror
has no effect). Moreover, this method won't help if you really want to avoid evaluating all the cases (e.g. if the calculations involved would be very time-consuming). An alternative is to avoid the use of
piecewise
, instead defining a procedure using an
if
statement.
> f:= x -> if not type(x,numeric) then 'f(x)' elif x < 1 then 1 else 1/x fi:
> f(0);
Note that the first condition
not type(x,numeric)
is needed to allow the use of
f(x)
when
x
is a symbolic variable or expression, for which the
x < 1
test would not return a value of
or
.
> f(x);
See also: if , piecewise , traperror
Maple Advisor Database, R. Israel 1997