Search code examples
latexalignment

How to align piecewise functions


I thought a properly aligned piecewise function should be something like this:

Properly aligned piecewise function

Commas and character xs are perfectly aligned in two lines.

I tried

\vert x \vert =
\begin{cases} 
  x, &x \geq 0 \\
 -x, &x < 0  \\
\end{cases}

which only aligned the domain parts like this:

Domain parts aligned

In that way, the commas come after x and -x is not aligned, which looks strange.

I tried to solve that problem by adding spaces preceding the x in first line, which is:

\vert x \vert =
\begin{cases} 
 \enspace \; x, &x \geq 0 \\
 -x, &x < 0  \\
\end{cases}

It gives the correct result (as above) but this solution seems rather strange, if the second line changes, then the first line have also to be modified to keep the spaces fit. I reckon there must be some better way to do it.


Solution

  • The default alignment behaviour of cases is left-left for the value and domain components. In this specific case (for aesthetic reasons), you can insert a \phantom negation to align the values:

    enter image description here

    \documentclass{article}
    
    \usepackage{amsmath}
    
    \begin{document}
    
    \[
      \lvert x \rvert = \begin{cases}
         x, & x \geq 0 \\
        -x, & x < 0
      \end{cases}
    \]
    
    \[
      \lvert x \rvert = \begin{cases}
        \phantom{-}x, & x \geq 0 \\
        -x, & x < 0
      \end{cases}
    \]
    
    \end{document}