Math and Equations

How to Write Piecewise Functions in LaTeX with the cases Environment

Write piecewise functions in LaTeX with the cases environment from amsmath, plus dcases for full-size fractions and an array-based fallback without packages.

On this page
  1. A basic piecewise function
  2. Conditions in words
  3. Full-size fractions with dcases
  4. Without amsmath: array with \left{ and \right.
  5. Common mistakes

Use the cases environment from amsmath. Each row holds an expression, then &, then its condition, and \\ ends the row.

A basic piecewise function

\[
  f(x) =
  \begin{cases}
    x^2    & \text{if } x < 0 \\
    0      & \text{if } x = 0 \\
    2x + 1 & \text{if } x > 0
  \end{cases}
\]
  • & separates the expression column from the condition column.
  • \\ ends each row. The last row does not need one.
  • cases draws the left brace for you.

Conditions in words

Words in a condition need \text{}. Without it, the letters in if are set as math variables, with no space after them:

x^2 & \text{if } x < 0

The trailing space inside \text{if } separates the word from the math that follows. For a final case, use \text{otherwise}:

0 & \text{otherwise}

Full-size fractions with dcases

cases shrinks fractions to fit the line. To keep them at full size, load mathtools and use dcases:

\usepackage{mathtools}

\[
  g(x) =
  \begin{dcases}
    \frac{1}{x} & \text{if } x \neq 0 \\
    0           & \text{if } x = 0
  \end{dcases}
\]

rcases from mathtools places the brace on the right instead.

Without amsmath: array with \left{ and \right.

If you cannot load amsmath, build the same layout with an array inside \left\{ ... \right.:

\[
  f(x) = \left\{
  \begin{array}{ll}
    -x & \mbox{if } x < 0 \\
    x  & \mbox{if } x \geq 0
  \end{array}
  \right.
\]

\mbox works without amsmath, so use it in place of \text in this version. The \right. closes the brace without printing one. The same brace-and-array pattern is used for systems of equations in aligning equations with align. Sizing brackets and parentheses explains the delimiter pair in more detail.

Common mistakes

  • Missing &: without it, the expression and the condition run together on one line.
  • Missing \text: the condition’s words come out as math italics with no spacing.
  • Inline cases: cases in running text is small and cramped. Use \[...\] instead, or dcases for fractions.
  • Missing \right.: the array version needs it, or LaTeX reports a missing \right..

Fractions inside cases are covered in how to write fractions in LaTeX. For the wider set of math topics in this cluster, see the advanced mathematics guide.

The complete guide to math and equations

Advanced Mathematics in LaTeX: Operators, Theorems and Proofs
Read the guide

Keep exploring

Guides from other topics

All topics →