### 4.6.2 Defining piecewise defined functions

You can use Xcas’s control structures to define functions not given by a single simple formula. Notably, you can use the ifte command or ? : operator to define piecewise-defined functions.

The ifte command takes three arguments; the first argument is a condition, the second argument tells the command what to return when the condition is true, and the third argument tells the command what to return when the condition is false. For example, you could define your own absolute value function with

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

Afterwards, for example, entering

> myabs(-4)

will return

> 4

However, this will return an error if it can’t evaluate the conditional. For example, if you enter

> myabs(x)

you will get the error

> Ifte: Unable to check test Error: Bad Argument Value

The ?: construct behaves similarly to ifte but is structured differently. Here, the condition comes first, followed by ?, then what to return if the condition is true, followed by the :, and then what to return if the condition is false. You could define your absolute value function with

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

If you enter

> myabs(-4)

you will again get

> 4

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

> myabs(x)

will return

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

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

> (condition)? true-result: false-result

> when(condition, true-result, false-result)

and

> IFTE(condition, true-result, false-result)

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 arguments to this function are alternately conditions and results to return if the condition is true, with the last argument being what to return if none of the conditions are true. For example, to define the function given by

f(x) = |
⎧ ⎪ ⎨ ⎪ ⎩ |
−2 | if x < −2
3x+4 | if −2 ≤ x < −1
1 | if −1 ≤ x < 0
x + 1 | if x ≥ 0

you can enter

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