[Tex/LaTex] What does the tilde character (~) do in math mode

math-modespacingtilde

What effect does the tilde character ~ have in math mode? Is it the same non-breaking space that it is in text mode? Is it bad style to use ~ in math mode? I've seen it used in some examples but have not seen it explained in any of the usual LaTeX references.

Best Answer

Using ~ or \⍽ (control space, just in order to make it clear) in math mode is not equivalent, as the following example shows:

\documentclass{article}
\begin{document}

$a=\ =b$

$a=~=b$

\end{document}

This produces

enter image description here

Why is that? Because the definition of ~ is

1299 \DeclareRobustCommand{\nobreakspace}{%
1300    \leavevmode\nobreak\ }
1301 \catcode `\~=13
1302 \def~{\nobreakspace{}}

(line numbers are those in latex.ltx). Thus ~ also adds a {} group that's significant in math mode and explains the difference in output: in the first line we have (Ord stands for an atom of class “ordinary”, Rel for an atom of class “binary relation”)

Ord Rel <skip> Rel Ord

and TeX ignores explicit skips when deciding what math spacing to insert. So by rule it inserts a thick space between Ord and Rel and between Rel and Ord, but no space between Rel and Rel. The <skip> due to \⍽ is inserted back when converting the math list to a horizontal box.

In the second case we have

Ord Rel <skip> Ord Rel Ord

because in math mode {} counts as an Ord atom. Thick spaces will be inserted at either side of the empty Ord atom.

Thus it's better to use \⍽ instead of ~, in order to avoid surprises. However, the usage should be limited to separating parts of a formula that need to be considered as words, typically in displays. There's no difference between

\[
\sin\pi = 0\ \text{and}\ \cos\pi = -1
\]

and

\[
\sin\pi = 0 \text{ and } \cos\pi = -1
\]

Just a question of personal preference, because either will use the interword space relative to the current font outside of math, without stretching or shrinking. For spacing math symbols the best is to use \mkern or \mskip (possibly the latter, for which amsmath provides the \mspace interface, analog to \hspace).

Note that in inline math mode \⍽\text{and}\⍽ and \text{⍽and⍽} are different, as the former inserts spaces that may participate to stretching and shrinking, whereas the latter inserts “frozen” spaces. However, something like

the set $N_n(R)=\{\,x\in R: x^{n-1}\ne 0\ \text{and}\ x^{n}=0\,\}$

is more properly written as

the set $N_n(R)=\{\,x\in R: x^{n-1}\ne 0$ and~$x^{n}=0\,\}$

so as to give TeX more chances to properly break the line.