Previous Up Next

5.1.3  Defining functions with boolean tests

use boolean tests to define functions not given by a single simple formula. Notably, use the ifte command or the ?: operator to define piecewise-defined functions.

Example

You can define your own absolute value function with:

myabs(x):=ifte(x>=0,x,-x)

Hence:

myabs(-4)
     
4           

However, myabs will return an error if it cannot evaluate the condition.

myabs(x)
     
Ifte: Unable to check test Error: Bad Argument Value           

The ?: construct behaves similarly to ifte, but is structured differently and does not return an error if the condition cannot be evaluated.

Example

You can define your absolute value function with

myabs(x):=(x>=0)?x:-x

If you enter

myabs(-4)

you will again get

     
4           

but now if the conditional cannot be evaluated, you won’t get an error.

myabs(x)
     
x≥ 0 ? x : −x           

The when and IFTE commands are prefixed synonyms for the ?: construct.

(condition) ? restrue : resfalse
when(condition,restrue,resfalse)

and

IFTE(condition,restrue,resfalse)

all represent the same expression.

If you want to define a function with several pieces, it may be simpler to use the piecewise function. The latter can also be used for finding piecewise representations of expressions.

Examples

To define

  f(x)=




    −2if  x < −2
    3x+4if  −2 ≤ x < −1
    1if  −1 ≤ x < 0
    x+1if  x ≥ 0

enter:

f(x):=piecewise(x<-2,-2,x<-1,3*x+4,x<0,1,x+1)

To verify, plot f(x) for e.g. −3≤ x≤ 1.

To convert the expression x θ(x+1)−x2 θ(x−1)+x3 sign(x) to a piecewise expression, enter:

f:=x*Heaviside(x+1)-x^2*Heaviside(x-1)+x^3*sign(x):;

and then

piecewise(f)

or:

piecewise(f,x)
     




x3,−1>x
x3+x,0>x
x3+x,1>x
x3x2+x,otherwise
          

piecewise can be used for “flattening” expressions containing piecewise defined subexpressions. For example:

piecewise(1+piecewise(x<0,-x,x<1,x,1)*when(x<1/2,4x^2,2-2x),x)
     








−4 x3+1,0>x
x3+1,
1
2
>x
−2 x2+2 x+1,1>x
−2 x+3,otherwise
          

Previous Up Next