Desmos Wiki (Unofficial)

Piecewises

Piecewise functions are the "if-statements" of Desmos, allowing you to add arbitrary conditional logic to your Desmos expressions.

Branching #

Piecewises can be used to add multiple "branches" to a Desmos expression, choosing which expression to evaluate based on a comparison. For instance, this piecewise evaluates to if is greater than 0, if is less than 0, and 0 if neither of these conditions apply.

Left-to-right Evaluation #

Piecewises are evaluated left-to-right. That is, they will try the leftmost condition first, then the next one, then the next one, then the next one, et cetera. That means that if you have more than one true condition in a piecewise, only the first one will be chosen.

This example, for instance, evaluates to 3, even though the branch would suggest that it could evaluate to 4. This is because the branch is the leftmost true branch.

Default Values and Domain Restrictions #

Piecewises have special behavior if the is omitted, allowing them to be used as domain restrictions. Consider the following graph:

The line is drawn only where is greater than -2. This is possible because— without anything after the to evaluate to, the piecewise defaults to evaluating to 1, effectively keeping its input the same under multiplication. However, if no condition is given and there is no fallback branch at the end without a condition, the piecewise will default to NaN (Not a Number) instead. NaN multiplied by anything is also NaN, so the line disappears.

Logical Operators #

Unfortunately, Desmos doesn't support logical operators (AND, OR, NOT, etc.) natively. However, you can emulate them by nesting piecewises. For simplicity's sake, the first condition in these examples will be notated and the second will be notated , but these could really be any conditions. represents the value to return if true; represents what to return if false.

AND #

OR #

NOT #

Logical Operators with Clever Conditions #

Alternatively, you can define your own custom boolean type where (for example) 0 represents "false" and 1 represents "true". With numbers representing booleans, you can create logical operators accordingly and use them in piecewises by testing if a value is equal to 1 or 0.

AND #

OR #

NOT #

Use with Actions #

Actions can be placed within piecewises to cause them to run conditionally. For instance, try using the following piecewise action, which will increment until it reaches 3.

Multiple actions can be encased in a piecewise, but take care to surround them with parentheses where necessary. These two actions mean different things:

In this first one, is the fallback condition that runs if the condition is false.

In this second one, both actions run when , and nothing runs if that's false.