Jean Gregory
Jean Gregory

Reputation: 398

Is there a way to center align part of an equation in latex?

I'm writing the steps to resolve an equation and for clarity I would like to align and center the part resolved on the second line with the part that was resolved on the first line. Is there a way to achive this?

For example, take this simple line

||-3 - 4 - 2| - 5|

which will resolve with the first step to

||-9| - 5|

I would like to render like this:

||-3 - 4 - 2| - 5|
|     |-9|    - 5|
|       9     - 5|

Is it doable ?

Upvotes: 1

Views: 5346

Answers (1)

Werner
Werner

Reputation: 15065

You can use eqparbox's \eqmakebox[<tag>][<align>]{<stuff>} to set <stuff> in the widest box possible across all similar <tag>s. Additionally, you can adjust the box's <align>ment as needed (default is centre, but there's also left and right). I've adapted \eqmakebox into \eqmathbox to work inside math mode:

enter image description here

\documentclass{article}

\usepackage{amsmath,eqparbox,xparse}

% https://tex.stackexchange.com/a/34412/5764
\makeatletter
\NewDocumentCommand{\eqmathbox}{o O{c} m}{%
  \IfValueTF{#1}
    {\def\eqmathbox@##1##2{\eqmakebox[#1][#2]{$##1##2$}}}
    {\def\eqmathbox@##1##2{\eqmakebox{$##1##2$}}}
  \mathpalette\eqmathbox@{#3}
}
\makeatother

\newcommand{\abs}[1]{\lvert #1 \rvert}

\begin{document}

\begin{align*}
  & \abs{\eqmathbox[eqn1]{\underbrace{\abs{-3 - 4 - 2}}} - 5} \\
  & \abs{  \eqmathbox[eqn1]{\underbrace{\abs{-9}}}       - 5} \\
  & \abs{         \eqmathbox[eqn1]{9}                    - 5}
\end{align*}

\end{document}

\underbrace is perhaps not necessary, but it's added for clarity in terms of the reduction.

The above can also be achieved inside an array:

enter image description here

\documentclass{article}

\usepackage{amsmath}
\newcommand{\abs}[1]{\lvert #1 \rvert}

\begin{document}

\[
  \begin{array}{ c @{} c @{} c }
    \lvert & \underbrace{\abs{-3 - 4 - 2}} & {} - 5 \rvert \\
    \lvert &    \underbrace{\abs{-9}}      & {} - 5 \rvert \\
    \lvert &             9                 & {} - 5 \rvert
  \end{array}
\]

\end{document}

The (vertical) spacing is slightly tighter by default.

Upvotes: 4

Related Questions