\Underbar changing the style of font but \bar not, why?

The difference is that \underbar switches to text mode when it boxes its contents. The definition in the kernel is

\def\underbar#1{\underline{\sbox\tw@{#1}\dp\tw@\z@\box\tw@}}

On the other side, \bar is a math accent:

\DeclareMathAccent{\bar}{\mathalpha}{operators}{"16}

You can define a variation of the kernel's \underbar that boxes the contents in math mode:

\documentclass[a4paper,english,titlepage,12pt]{article} 
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsthm}     %For theorems
\usepackage{amssymb}    %For things, \mathbb R.
\usepackage{bm}         %For bolding with greek letters

\makeatletter
\def\munderbar#1{\underline{\sbox\tw@{$#1$}\dp\tw@\z@\box\tw@}}
\makeatother

\begin{document}
\newbox\mybox
\begin{align}
l_i &= \bar{x}_i-\munderbar{x}_i \\
\hat x_i &= 0.5 (\bar{x}_i+\munderbar{x}_i)
\end{align}

\end{document}

enter image description here

However, as you can see in the image the result is not very good. A better alternative is to use the accents package and its \underaccent command:

\documentclass[a4paper,english,titlepage,12pt]{article} 
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsthm}     %For theorems
\usepackage{amssymb}    %For things, \mathbb R.
\usepackage{bm}         %For bolding with greek letters
\usepackage{accents}

\newcommand\munderbar[1]{%
  \underaccent{\bar}{#1}}

\begin{document}
\newbox\mybox
\begin{align}
l_i &= \bar{x}_i-\munderbar{x}_i \\
\hat x_i &= 0.5 (\bar{x}_i+\munderbar{x}_i)
\end{align}

\end{document}

enter image description here


You have two choices: either use \underline or the accents package and its \underaccent feature; I'll show both.

\documentclass[a4paper]{article}
\usepackage{amsmath}
\usepackage{accents}

\newcommand{\ubar}[1]{\underaccent{\bar}{#1}}

\begin{document}

\begin{align*}
l_i &= \bar{x}_i-\underline{x}_i \\
\hat{x}_i &= 0.5 (\bar{x}_i+\underline{x}_i)
\end{align*}

\begin{align*}
l_i &= \bar{x}_i-\ubar{x}_i \\
\hat{x}_i &= 0.5 (\bar{x}_i+\ubar{x}_i)
\end{align*}

\end{document}

enter image description here


Avoid \bar x or \hat x; with braces it may seem more difficult to type, but it adds to clarity.


You are making it harder than it has to be. \underbar{$x$} resolves it without further packages or new commands. To get equal length use \overline{x} instead of \bar{x}. The bars are longer than in the above, but equal.

Tags:

Fonts