Piecewise functions in LaTeX: cases, conditions, and numbering

BlogEasyLaTeXPublished

To write a piecewise function in LaTeX, load amsmath and use cases inside math mode. Write the value first, separate its condition with &, and start the next branch with \\. Enclose the definition in equation to give the whole function one equation number.

Start with a complete example

Save this as main.tex and compile with pdfLaTeX. This article document needs only amsmath. The separate package named cases is not required for this example.

LaTeX
\documentclass[a4paper,11pt]{article}\usepackage{amsmath}​\begin{document}\begin{equation}\label{eq:absolute}  |x| =  \begin{cases}    x,  & \text{if } x \ge 0, \\    -x, & \text{if } x < 0.  \end{cases}\end{equation}See equation~\eqref{eq:absolute}.\end{document}

The PDF should show a left brace, two rows of values and conditions, and one number for the entire definition. After references resolve, the number in the sentence should match the equation. Zero belongs to the first branch; negative numbers belong to the second. Every real input is covered once.

Structure diagram: the left column gives the value and the right column gives its condition. The boundary point 0 belongs to the first row.

Align conditions with & and separate branches with \\

  • & separates two left-aligned columns. Indentation spaces in the source do not align the columns in the PDF.
  • \\ starts a new branch. Usually omit it after the last row. An ordinary source-code newline does not create a new equation row.
  • \text{if } typesets the word as normal text. Keep the space inside the braces before the mathematical condition. Use \text{otherwise} for the remaining cases.
  • cases supplies the left brace. Do not add another \left\{. It must be inside math mode, such as \[...\] or equation. A multiline definition is generally easier to read as a displayed equation.

For example, this step function uses otherwise to cover x <= 0, including zero, over a real-valued domain:

LaTeX
\[s(x)=\begin{cases}  1, & \text{if } x > 0, \\  0, & \text{otherwise}.\end{cases}\]

Keep mathematical symbols in math mode. Typing the word if as math makes it a pair of italic variables; putting an entire mathematical condition into plain text also loses mathematical typesetting. The dcases* variant below uses a different rule for its right column.

A paper-writing example: Huber loss and boundary checks

Let r be a real residual and let the threshold satisfy δ > 0. Huber loss uses a quadratic term for small residuals and a term linear in the absolute residual for larger ones:

LaTeX
\[L_{\delta}(r) =\begin{cases}  \frac{1}{2}r^2, & \text{if } |r| \le \delta, \\  \delta\left(|r|-\frac{1}{2}\delta\right),    & \text{if } |r| > \delta.\end{cases}\]

The first branch includes |r| = δ; the second applies only when |r| > δ. Both expressions equal δ²/2 at the boundary, although the conditions assign that point only to the first branch. With δ = 1, residuals r = 0, 1, and 2 give losses 0, 0.5, and 1.5.

When adapting the example, write down the domain and check every boundary. Two strict inequalities can leave a point uncovered; two inclusive inequalities can overlap. Successful compilation cannot check those mathematical conditions.

Small fractions: cases or dcases?

Ordinary cases uses \textstyle. Its \frac remains compact even inside a displayed equation. For larger fractions, sums, or integrals, replace \usepackage{amsmath} in the preamble with \usepackage{mathtools} and use dcases. The mathtools package loads amsmath automatically.

Insert this fragment into the body of a document that loads mathtools to compare two layouts of the same function:

LaTeX
\[g(x)=\begin{cases}  \frac{1}{1+x^2}, & x \ge 0, \\  0, & x < 0.\end{cases}\qquadg(x)=\begin{dcases}  \frac{1}{1+x^2}, & x \ge 0, \\  0, & x < 0.\end{dcases}\]

Style comparison diagram: the definition and conditions stay the same. Display-style dcases gives the fraction more height and increases row spacing. Check the actual output in your template.

If only one fraction needs enlarging, replace \frac with \dfrac inside cases. That changes the individual fraction; dcases sets the branch expressions in display style. Check spacing and column width before choosing, particularly in narrow columns.

The right column of dcases* is text

In dcases, the condition column is still math, so words need \text{...}. In dcases*, that column is ordinary text and mathematical conditions go inside $...$:

LaTeX
\[g(x)=\begin{dcases*}  \frac{1}{1+x^2}, & if $x \ge 0$, \\  0, & otherwise.\end{dcases*}\]

Both variants come from mathtools. When changing the environment name, update the condition syntax too.

Number the whole function or each branch

NeedConstructionPackage and nesting
No numbercases inside \[...\]amsmath
One number for the definitioncases inside equationUse \label and \eqref
Separate numbers for branchesnumcasesLoad the cases package; this is a display environment itself
Lettered numbers in one groupsubnumcasescases package, for example (1a) and (1b)

One number usually suffices for a function definition. If the text needs to cite individual branches, load \usepackage{amsmath} and \usepackage{cases} in the preamble, then insert:

LaTeX
\begin{numcases}{h(x)=}  x,  & if $x \ge 0$ \label{eq:positive} \\  -x, & if $x < 0$ \label{eq:negative}\end{numcases}See equations~\eqref{eq:positive} and~\eqref{eq:negative}.

The argument {h(x)=} supplies the expression to the left of the brace. The right column is text by default, so mathematical conditions need $...$. Do not wrap numcases in equation or \[...\]. Each row's \label refers to its own number. For lettered suffixes, change the environment to subnumcases and check the references again.

See equation numbering and references for more on labels.

Troubleshoot by symptom

SymptomCheckFix
Math-mode or alignment errorsEnclosing math environment and amsmathRestore the complete example's package and outer environment
Environment dcases undefinedOnly amsmath is loadedLoad mathtools
Values and conditions run togetherMissing &Separate value and condition with one & per row
Branches appear on one lineMissing \\Add two backslashes between branches
Extra alignment tab or related errorToo many & charactersKeep ordinary cases to two columns
Italic if or otherwise, missing spacesWords entered as mathUse \text{...} in ordinary cases
Two left bracesAn extra manual \left\{Keep the brace supplied by cases
References show ??Label spelling, numbered environment, compile passesCheck \label, compile again, and read the log

These symptoms can have other causes. Start with the first error in the log and the source around it, rather than changing code based only on the last message.

Verify locally or in EasyLaTeX

With TeX Live or MiKTeX, run these commands in the directory containing main.tex:

Shell
pdflatex -interaction=nonstopmode -halt-on-error main.texpdflatex -interaction=nonstopmode -halt-on-error main.tex

Read main.log for errors, unresolved references, and Overfull \hbox. Open the newly generated main.pdf and inspect the brace, condition column, fraction sizes, and numbering. Substituting the three residuals for δ = 1 also helps catch a mistyped coefficient in the Huber example.

In EasyLaTeX, put the example in the project's main file, confirm that the correct main file is selected, and choose pdfLaTeX for this English article example. Wait for compilation. For errors, use the Bug panel and Original Log. You can give Agent the relevant source and log for help locating a problem; review its changes and compile again. Keep the appropriate compiler and template settings in an existing multilingual or journal project.

The complete minimal document and the other five code fragments were compiled with pdfLaTeX on TeXLive.net, and the logs and PDFs were checked. They were not tested in the product compiler or a particular journal template. Check package compatibility and the current PDF when merging them into a manuscript.

For related syntax, see scripts, fractions, brackets, and matrices. Continue with equation line breaks for long expressions or compilation troubleshooting for persistent errors.

References