User:Clebell/Sandbox

From Wikibooks, open books for an open world
Jump to: navigation, search
LaTeX logo.svg

LaTeX

Getting Started
  1. Introduction
  2. Installation
  3. Installing Extra Packages
  4. Basics

Common Elements

  1. Document Structure
  2. Text Formatting
  3. Paragraph Formatting
  4. Colors
  5. Fonts
  6. List Structures
  7. Special Characters
  8. Internationalization
  9. Rotations
  10. Tables
  11. Title creation
  12. Page Layout
  13. Importing Graphics
  14. Floats, Figures and Captions
  15. Footnotes and Margin Notes
  16. Hyperlinks
  17. Labels and Cross-referencing

Mechanics

  1. Errors and Warnings
  2. Lengths
  3. Counters
  4. Boxes
  5. Rules and Struts

Technical Texts

  1. Mathematics
  2. Advanced Mathematics
  3. Theorems
  4. Chemical Graphics
  5. Algorithms
  6. Source Code Listings
  7. Linguistics

Special Pages

  1. Indexing
  2. Glossary
  3. Bibliography Management
  4. More Bibliographies

Special Documents

  1. Letters
  2. Presentations
  3. Teacher's Corner
  4. Curriculum Vitae

Creating Graphics

  1. Introducing Procedural Graphics
  2. MetaPost
  3. Picture
  4. PGF/TikZ
  5. PSTricks
  6. Xy-pic
  7. Creating 3D graphics

Programming

  1. Macros
  2. Plain TeX
  3. Creating Packages
  4. Themes

Miscellaneous

  1. Modular Documents
  2. Collaborative Writing of LaTeX Documents
  3. Export To Other Formats

Help and Recommendations

  1. FAQ
  2. Tips and Tricks

Appendices

  1. Authors
  2. Links
  3. Package Reference
  4. Sample LaTeX documents
  5. Index
  6. Command Glossary

edit this boxedit the TOC

Sandbox Document[edit]

This is a copy of a section from the LaTeX Wikibook. It is here to be edited in private so as not to interfere with the live Wikibook. This document is not for public consumption.

--Clebell (discusscontribs) 15:24, 6 March 2011 (UTC)

Mathematical typesetting is one of LaTeX's greatest strengths.

Math Packages[edit]

If your document requires only a few simple mathematical formulas, plain LaTeX has most of the tools that you will need. If you are writing a scientific document that contains numerous complicated formulas, packages are available that introduce commands that are more powerful and flexible than the ones provided by LaTeX.

TODO: List packages that are used in the examples.

Math Environments[edit]

LaTeX uses environments to typeset mathematical notation. They can be separated into two categories based on how formulas are presented:

  • text - text formulas are displayed in-line, that is, within the body of text where it is declared. e.g., I can say that a + a = 2a within this sentence.
  • displayed - displayed formulas are separate from the main text.

As maths require special environments, there are naturally the appropriate environment names you can use in the standard way. Unlike most other environments, however, there are some handy shorthands to declaring your formulas. The following table summarizes them:

Type Environment LaTeX shorthand TeX shorthand
Text \begin{math}...\end{math} \(...\) $...$
Displayed \begin{displaymath}...\end{displaymath} or

\begin{equation*}...\end{equation*}[1]

\[...\] $$...$$

Note: Using the $$...$$ should be avoided, as it may cause problems, particularly with the AMS-LaTeX macros. Furthermore, should a problem occur, the error messages may not be helpful.

Additionally, there is a second possible environment for the displayed type of formulas: equation. The difference between this and displaymath is that equation also adds sequential equation numbers by the side.

If you are typing text normally, you are said to be in text mode, while you are typing within one of those mathematical environments, you are said to be in math mode, that has some differences compared to the text mode:

  1. Most spaces and line breaks do not have any significance, as all spaces are either derived logically from the mathematical expressions, or have to be specified with special commands such as \quad
  2. Empty lines are not allowed. Only one paragraph per formula.
  3. Each letter is considered to be the name of a variable and will be typeset as such. If you want to typeset normal text within a formula (normal upright font and normal spacing) then you have to enter the text using dedicated commands.

Inserting "Displayed" maths inside blocks of text[edit]

In order for some operators, such as \lim or \sum to be displayed correctly inside some math environments (read $......$), it might be convenient to write the \displaystyle class inside the environment. Doing so might cause the line to be taller, but will cause exponents and indices to be displayed correctly for some math operators

Symbols[edit]

Mathematics has lots and lots of symbols! If there is one aspect of maths that is difficult in LaTeX it is trying to remember how to produce them. There are of course a set of symbols that can be accessed directly from the keyboard:

+ - = ! / ( ) [ ] < > | ' :

Beyond those listed above, distinct commands must be issued in order to display the desired symbols. And there are a lot! of Greek letters, set and relations symbols, arrows, binary operators, etc. For example:

\[
 \forall x \in X, \quad \exists y \leq \epsilon
\
]


\forall x \in X, \quad \exists y \leq \epsilon
 \,

Fortunately, there's a tool that can greatly simplify the search for the command for a specific symbol. Look for Detexify in the external links section below.

Greek letters[edit]

Greek letters are commonly used in mathematics, and they are very easy to type in math mode. You just have to type the name of the letter after a backslash: if the first letter is lowercase, you will get a lowercase Greek letter, if the first letter is uppercase (and only the first letter), then you will get an uppercase letter. Note that some uppercase Greek letters look like Latin ones, so they are not provided by LaTeX (e.g. uppercase Alpha and Beta are just "A" and "B" respectively). Lowercase epsilon, theta, phi, pi, rho, and sigma are provided in two different versions. The alternate, or variant, version is created by adding "var" before the name of the letter:

\[
 \alpha, \beta, \gamma, \delta, \epsilon, \varepsilon,
 \zeta, \eta, \theta, \vartheta, \iota, \kappa, \lambda,
 \mu, \nu, \xi, \pi, \varpi, \rho, \varrho, \sigma, \varsigma,
 \tau, \upsilon, \phi, \varphi, \chi, \psi, \omega,
 \Gamma, \Delta, \Theta, \Phi, \Omega
\
]

\alpha, \beta, \gamma, \delta, \epsilon, \varepsilon,
 \zeta, \eta, \theta, \vartheta, \iota, \kappa, \lambda,
 \mu, \nu, \xi, \pi, \varpi, \rho, \varrho, \sigma, \varsigma,
 \tau, \upsilon, \phi, \varphi, \chi, \psi, \omega,

 \Gamma, \Delta, \Theta, \Phi, \Omega

Operators[edit]

An operator is a function that is written as a word: e.g. trigonometric functions (sin, cos, tan), logarithms and exponentials (log, exp). LaTeX has many of these defined as commands:

\[
 \cos (2\theta) = \cos^2 \theta - \sin^2 \theta
\
]

\cos (2\theta) = \cos^2 \theta - \sin^2 \theta \,

For certain operators such as limits, the subscript is placed underneath the operator:

\[
 \lim_{x \to \infty} \exp(-x) = 0
\
]

\lim_{x \to \infty} \exp(-x) = 0

For the modular operator there are two commands: \bmod and \pmod:

\[
 a \bmod b
\
]


 a \, \bmod \, b
\,

\[
 x \equiv a \pmod b
\
]


 x \equiv a \pmod b
\,

To use operators which are not pre-defined, such as argmax, see custom operators

Powers and indices[edit]

Powers and indices are equivalent to superscripts and subscripts in normal text mode. The caret (^) character is used to raise something, and the underscore (_) is for lowering. If more than one expression is raised or lowered, they should be grouped using curly braces ({ and }).

\[
 k_{n+1} = n^2 + k_n^2 - k_{n-1}
\
]


k_{n+1} = n^2 + k_n^2 - k_{n-1}
 \,

An underscore (_) can be used with a vertical bar (|) to denote evaluation using subscript notation in mathematics:

\[
 f(n) = n^5 + 4n^2 + 2 |_{n=17}
\
]


 f(n) = n^5 + 4n^2 + 2 |_{n=17}
 \,

Fractions and Binomials[edit]

A fraction is created using the \frac{numerator}{denominator} command. (for those who need their memories refreshed, that's the top and bottom respectively!). Likewise, the binomial coefficient (aka the Choose function) may be written using the \binom command[1]:

\[
 \frac{n!}{k!(n-k)!} = \binom{n}{k}
\
]


\frac{n!}{k!(n-k)!} = \binom{n}{k}

It is also possible to use the \choose command without the amsmath package:

\[
 \frac{n!}{k!(n-k)!} = {n \choose k}
\
]


 \frac{n!}{k!(n-k)!} = {n \choose k}

You can embed fractions within fractions:

\[
 \frac{\frac{1}{x}+\frac{1}{y}}{y-z}
\
]


\frac{\frac{1}{x}+\frac{1}{y}}{y-z}

Note that when appearing inside another fraction, or in inline text \tfrac{a}{b}, a fraction is noticeably smaller than in displayed mathematics. The \tfrac and \dfrac commands[1] force the use of the respective styles, \textstyle and \displaystyle. Similarly, the \tbinom and \dbinom commands typeset the binomial coefficient.

Another way to write fractions is to use the \over command without the amsmath package:

\[
 {n! \over k!(n-k)!} = {n \choose k}
\
]


 {n! \over k!(n-k)!} = {n \choose k}

For relatively simple fractions, it may be more aesthetically pleasing to use powers and indices:

\[
 ^3/_7
\
]


^3/_7
 \,

If you use them throughout the document, usage of xfrac package is recommended. This package provides \sfrac command to create slanted fractions. Usage:

Take \sfrac{1}{2} cup of sugar, \dots
 \[
  3\times\sfrac{1}{2}=1\sfrac{1}{2}
 \
]

Take ${}^1/_2$ cup of sugar, \dots
 \[
  3\times{}^1/_2=1{
}^1/_2
 \
]

LaTeX-xfrac-example.png

Alternatively, the nicefrac package provides the \nicefrac command, whose usage is similar to \sfrac.

Continued fractions[edit]

Continued fractions should be written using \cfrac command[1]:

\begin{equation}
  x = a_0 + \cfrac{1}{a_1
          + \cfrac{1}{a_2
          + \cfrac{1}{a_3 + a_4}}}
\end{equation
}

   x = a_0 + \cfrac{1}{a_1 
           + \cfrac{1}{a_2 
           + \cfrac{1}{a_3 + a_4}}}

Roots[edit]

The \sqrt command creates a square root surrounding an expression. It accepts an optional argument specified in square brackets ([ and ]) to change magnitude:

\[
\sqrt{\frac{a}{b}}
\
]


\sqrt{\frac{a}{b}}

\[
\sqrt[n
]{1+x+x^2+x^3+\ldots}
\]


\sqrt[n]{1+x+x^2+x^3+\ldots}


Some people prefer writing the square root "closing" it over its content. This method arguably makes it more clear just what is in the scope of the root sign. This habit is not normally used while writing with the computer, but if you still want to change the output of the square root, LaTeX gives you this possibility. Just add the following code in the preamble of your document:

% New definition of square root:
% it renames \sqrt as \oldsqrt
\let\oldsqrt\sqrt
% it defines the new \sqrt in terms of the old one
\def\sqrt{\mathpalette\DHLhksqrt}
\def\DHLhksqrt#1#2{%
\setbox0=\hbox{$#1\oldsqrt{#2\,}$}\dimen0=\ht0
\advance\dimen0-0.2\ht0
\setbox2=\hbox{\vrule height\ht0 depth -\dimen0
}%
{\box0\lower0.4pt\box2}}

The new style is on left, the old one on right

This TeX code first renames the \sqrt command as \oldsqrt, then redefines \sqrt in terms of the old one, adding something more. The new square root can be seen in the picture on the right, compared to the old one. Unfortunately this code won't work if you want to use multiple roots: if you try to write \sqrt[b]{a} as \sqrt[b]{a} after you used the code above, you'll just get a wrong output. In other words, you can redefine the square root this way only if you are not going to use multiple roots in the whole document.

Sums and integrals[edit]

The \sum and \int commands insert the sum and integral symbols respectively, with limits specified using the caret (^) and underscore (_):

\[
 \sum_{i=1}^{10} t_i
\
]


\sum_{i=1}^{10} t_i 
 \,

\[
 \int_0^\infty e^{-x}\,dx
\
]


\int_0^\infty e^{-x}\,dx
 \,

There are many other "big" commands which operate in a similar manner:

\sum \sum \, \prod \prod \coprod \coprod
\bigoplus \bigoplus \bigotimes \bigotimes \bigodot \bigodot
\bigcup \bigcup \bigcap \bigcap \biguplus \biguplus
\bigsqcup \bigsqcup \bigvee \bigvee \bigwedge \bigwedge
\int \int \oint \oint \iint[1] \iint
\iiint[1] \iiint \iiiint[1] \iiiint \idotsint[1] \int \! \cdots \! \int

For more integral symbols, including those not included by default in the Computer Modern font, try the esint package.

The \substack command[1] allows the use of \\ to write the limits over multiple lines:

\[
 \sum_{\substack{
   0<i<m \\
   0<j<n
  }
}
 P(i,j)
\
]


\sum_{\overset{\scriptstyle 0<i<m} {\scriptstyle 0<j<n}} P(i,j)
 \,

If you want the limits of an integral to be specified above and below the symbol (like the sum), use the \limits command:

\[
 \int\limits_a^b
\
]


\int\limits_a^b
 \,

However if you want this to apply to ALL integrals, it is preferable to specify the intlimits option when loading the amsmath package:

\usepackage[intlimits]{amsmath}

Subscripts and superscripts in other contexts as well as other parameters to amsmath package related to them are described in Advanced Mathematics chapter.

For bigger integrals, you may use personal declarations, or the bigints package [2].

Brackets, braces and delimiters[edit]

How to use braces in multi line equations is described in the Advanced Mathematics chapter.

The use of delimiters such as brackets soon becomes important when dealing with anything but the most trivial equations. Without them, formulas can become ambiguous. Also, special types of mathematical structures, such as matrices, typically rely on delimiters to enclose them.

There are a variety of delimiters available for use in LaTeX:

\[
 () \, [
] \, \{\} \, || \, \|\| \,
 \langle\rangle \, \lfloor\rfloor \, \lceil\rceil
\
]


() \, [] \, \{\} \, || \, \|\| \, \langle\rangle \, \lfloor\rfloor \, \lceil\rceil
 \,

Automatic sizing[edit]

Very often mathematical features will differ in size, in which case the delimiters surrounding the expression should vary accordingly. This can be done automatically using the \left and \right commands. Any of the previous delimiters may be used in combination with these:

\[
 \left(\frac{x^2}{y^3}\right)
\
]


\left(\frac{x^2}{y^3}\right)
 \,

If a delimiter on only one side of an expression is required, then an invisible delimiter on the other side may be denoted using a period (.).

Manual sizing[edit]

In certain cases, the sizing produced by the \left and \right commands may not be desirable, or you may simply want finer control over the delimiter sizes. In this case, the \big, \Big, \bigg and \Bigg modifier commands may be used:

\[
 ( \big( \Big( \bigg( \Bigg(
\
]


( \big( \Big( \bigg( \Bigg( 
 \,

Matrices and arrays[edit]

A basic matrix may be created using the matrix environment[1]: in common with other table-like structures, entries are specified by row, with columns separated using an ampersand (&) and a new rows separated with a double backslash (\\)

\[
 \begin{matrix}
  a & b & c \\
  d & e & f \\
  g & h & i
 \end{matrix
}
\
]


\begin{matrix}
a & b & c \\
d & e & f \\
g & h & i
\end{matrix}

To specify alignment of columns in the table, use starred version[3]:

\[
 \begin{matrix}
  -1 & 3 \\
  2 & -4
 \end{matrix}
 =
 \begin{matrix*}[r
]
  -1 & 3 \\
  2 & -4
 \end{matrix*
}
\]


 \begin{matrix}
  -1 & 3 \\
  2 & -4
 \end{matrix}
 =
 \begin{matrix}
  -1 & \,\;\;3 \\
  \,\;\;2 & -4
 \end{matrix}

The alignment by default is c but it can be any column type valid in array environment.

However matrices are usually enclosed in delimiters of some kind, and while it is possible to use the \left and \right commands, there are various other predefined environments which automatically include delimiters:

Environment name Surrounding delimiter Notes
pmatrix[1] ( \, ) centers columns by default
pmatrix*[3] ( \, ) allows to specify alignment of columns in optional parameter
bmatrix[1] [ \, ] centers columns by default
bmatrix*[3] [ \, ] allows to specify alignment of columns in optional parameter
Bmatrix[1] \{ \, \} centers columns by default
Bmatrix*[3] \{ \, \} allows to specify alignment of columns in optional parameter
vmatrix[1] | \, | centers columns by default
vmatrix*[3] | \, | allows to specify alignment of columns in optional parameter
Vmatrix[1] \| \, \| centers columns by default
Vmatrix*[3] \| \, \| allows to specify alignment of colums in optional parameter

When writing down arbitrary sized matrices, it is common to use horizontal, vertical and diagonal triplets of dots (known as ellipses) to fill in certain columns and rows. These can be specified using the \cdots, \vdots and \ddots respectively:

\[
 A_{m,n} =
 \begin{pmatrix}
  a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\
  a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  a_{m,1} & a_{m,2} & \cdots & a_{m,n}
 \end{pmatrix
}
\
]


A_{m,n} = 
\begin{pmatrix}
a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\
a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\
\vdots  & \vdots  & \ddots & \vdots  \\
a_{m,1} & a_{m,2} & \cdots & a_{m,n} 
\end{pmatrix}

In some cases you may want to have finer control of the alignment within each column, or want to insert lines between columns or rows. This can be achieved using the array environment, which is essentially a math-mode version of the tabular environment, which requires that the columns be pre-specified:

\[
 \begin{array}{c|c}
  1 & 2 \\
  \hline
  3 & 4
 \end{array
}
\
]


\begin{array}{c|c}
1 & 2 \\ 
\hline
3 & 4
\end{array}

You may see that the AMS matrix class of environments doesn't leave enough space when used together with fractions resulting in output similar to this:


 M = \begin{bmatrix}
       \frac{5}{6} & \frac{1}{6} & 0\\
       \frac{5}{6} & 0           & \frac{1}{6}\\
       0           & \frac{5}{6} & \frac{1}{6}
     \end{bmatrix}

To counteract this problem, add additional leading space with the optional parameter to the \\ command:

\[
 M = \begin{bmatrix}
       \frac{5}{6} & \frac{1}{6} & 0           \\[0.3em
]
       \frac{5}{6} & 0           & \frac{1}{6} \\[0.3em]
       0           & \frac{5}{6} & \frac{1}{6}
     \end{bmatrix
}
\]


 M = \begin{bmatrix}
       \frac{5}{6} & \frac{1}{6} & 0           \\[0.3em]
       \frac{5}{6} & 0           & \frac{1}{6} \\[0.3em]
       0           & \frac{5}{6} & \frac{1}{6}
     \end{bmatrix}

If you need "border" or "indexes" on your matrix, plain TeX provides the macro \bordermatrix

\[
M = \bordermatrix{~ & x & y \cr
                  A & 1 & 0 \cr
                  B & 0 & 1 \cr
}
\
]

Bordermatrix.png


Matrices in running text[edit]

To insert a small matrix, and not increase leading in the line containing it, use smallmatrix environment:

A matrix in text must be set smaller
$\bigl(\begin{smallmatrix}
a&b\\ c&d
\end{smallmatrix
} \bigr)$

to not increase leading in a portion of text.

LaTeX-smallmatrix.png

Adding text to equations[edit]

The math environment differs from the text environment in the representation of text. Here is an example of trying to represent text within the math environment:

\[
 50 apples \times 100 apples = lots of apples^2
\
]


 50 apples \times 100 apples = lots of apples^2
\,

There are two noticeable problems: there are no spaces between words or numbers, and the letters are italicized and more spaced out than normal. Both issues are simply artifacts of the maths mode, in that it treats it as a mathematical expression: spaces are ignored (LaTeX spaces mathematics according to its own rules), and each character is a separate element (so are not positioned as closely as normal text).

There are a number of ways that text can be added properly. The typical way is to wrap the text with the \text{...} command [1] (a similar command is \mbox{...}, though this causes problems with subscripts, and has a less descriptive name). Let's see what happens when the above equation code is adapted:

\[
 50 \text{apples} \times 100 \text{apples}
 = \text{lots of apples
}^2
\
]


 50 \text{apples} \times 100 \text{apples} = \text{lots of apples}^2
\,

The text looks better. However, there are no gaps between the numbers and the words. Unfortunately, you are required to explicitly add these. There are many ways to add spaces between maths elements, but for the sake of simplicity you may literally add the space character in the affected \text(s) itself (just before the text.)

\[
 50 \text{ apples} \times 100 \text{ apples}
 = \text{lots of apples
}^2
\
]


 50 \text{ apples} \times 100 \text{ apples} = \text{lots of apples}^2
\,

Formatted text[edit]

Using the \text is fine and gets the basic result. Yet, there is an alternative that offers a little more flexibility. You may recall the introduction of font formatting commands, such as \textrm, \textit, \textbf, etc. These commands format the argument accordingly, e.g., \textbf{bold text} gives bold text. These commands are equally valid within a maths environment to include text. The added benefit here is that you can have better control over the font formatting, rather than the standard text achieved with \text.

\[
 50 \textrm{ apples} \times 100
 \textbf{ apples} = \textit{lots of apples
}^2
\
]


 50 \;\textrm{ apples} \times 100 \;\textbf{ apples} = \textit{lots}\;of\;apples^2
\,

Formatting mathematics symbols[edit]

So we can format text, what about formatting mathematics? There are a set of formatting commands very similar to the font formatting ones just used, except they are aimed specifically for text in maths mode (requires amsfonts)

LaTeX command Sample Description Common use
\mathnormal{} ABCDEF abcdef 123456\, the default math font most mathematical notation
\mathrm{} \mathrm{ABCDEF abcdef 123456}\, this is the default or normal font, unitalicised units of measurement, one word functions
\mathit{} \mathit{ABCDEF abcdef 123456}\, italicised font
\mathbf{} \mathbf{ABCDEF abcdef 123456}\, bold font vectors
\mathsf{} \mathsf{ABCDEF abcdef 123456}\, Sans-serif
\mathtt{} ABCDEFabcdef123456 Monospace (fixed-width) font
\mathcal{} \mathcal{ABCDEF abcdef 123456}\, Calligraphy (uppercase only) often used for sheaves/schemes and categories
\mathfrak{}[4] \mathfrak{ABCDEF abcdef 123456}\, Fraktur Almost canonical font for Lie algebras
\mathbb{}[4] \mathbb{ABCDEF abcdef 123456}\, Blackboard bold Used to denote special sets (e.g. real numbers)
\mathscr{}[5] Script

The maths formatting commands can be wrapped around the entire equation, and not just on the textual elements: they only format letters, numbers, and uppercase Greek, and the rest of the maths syntax is ignored.

To bold lowercase Greek or other symbols use the \boldsymbol command[1]; this will only work if there exists a bold version of the symbol in the current font. As a last resort there is the \pmb command[1] (poor mans bold): this prints multiple versions of the character slightly offset against each other

\[
 \boldsymbol{\beta} = (\beta_1,\beta_2,\ldots,\beta_n)
\
]


 \boldsymbol{\beta} = (\beta_1,\beta_2,\ldots,\beta_n)
\,

To change the size of the fonts in math mode, see Changing font size.

Accents[edit]

So what to do when you run out of symbols and fonts? Well the next step is to use accents:

a' a'\, a'' a''\, a''' a'''\, a'''' a''''\,
\hat{a} \hat{a} \, \bar{a} \bar{a} \, \overline{aaa} \overline{aaa} \, \check{a} \check{a} \, \tilde{a} \tilde{a} \,
\grave{a} \grave{a} \, \acute{a} \acute{a} \, \breve{a} \breve{a} \, \vec{a} \vec{a} \,
\dot{a} \dot{a} \, \ddot{a} \ddot{a} \, \dddot{a}[1] \ddddot{a}[1]
\not{a} \not{a} \, \mathring{a} \widehat{AAA} \widehat{AAA} \, \widetilde{AAA}

Plus and minus signs[edit]

Latex deals with the + and - signs in two possible ways. The most common is as a binary operator. When two maths elements appear either side of the sign, it is assumed to be a binary operator, and as such, allocates some space either side of the sign. The alternative way is a sign designation. This is when you state whether a mathematical quantity is either positive or negative. This is common for the latter, as in maths, such elements are assumed to be positive unless a - is prefixed to it. In this instance, you want the sign to appear close to the appropriate element to show their association. If you put a + or a - with nothing before it but you want it to be handled like a binary operator you can add an invisible character before the operator using {}. This can be useful if you are writing multiple-line formulas, and a new line could start with a = or a +, for example, then you can fix some strange alignments adding the invisible character where necessary.

Controlling horizontal spacing[edit]

LaTeX is obviously pretty good at typesetting maths—it was one of the chief aims of the core Tex system that LaTeX extends. However, it can't always be relied upon to accurately interpret formulas in the way you did. It has to make certain assumptions when there are ambiguous expressions. The result tends to be slightly incorrect horizontal spacing. In these events, the output is still satisfactory, yet, any perfectionists will no doubt wish to fine-tune their formulas to ensure spacing is correct. These are generally very subtle adjustments.

There are other occasions where LaTeX has done its job correctly, but you just want to add some space, maybe to add a comment of some kind. For example, in the following equation, it is preferable to ensure there is a decent amount of space between the maths and the text.

\[
  f(n) = \left\{
  \begin{array}{l l}
    n/2 & \quad \text{if $n$ is even}\\
    -(n+1)/2 & \quad \text{if $n$ is odd}\\
  \end{array
} \right.
\
]


f(n) =
\begin{cases}
n/2 & \quad \text{if } n \text{ is even} \\
-(n+1)/2 & \quad \text{if } n \text{ is odd}\\ 
\end{cases}

This code produces errors with Miktex 2.9 and does not yield the results seen on the right. Use \textrm instead of just \text.


(Note that this particular example can be expressed in more elegant code by the cases construct provided by the amsmath package described in Advanced Mathematics chapter.)

LaTeX has defined two commands that can be used anywhere in documents (not just maths) to insert some horizontal space. They are \quad and \qquad

A \quad is a space equal to the current font size. So, if you are using an 11pt font, then the space provided by \quad will also be 11pt (horizontally, of course.) The \qquad gives twice that amount. As you can see from the code from the above example, \quads were used to add some separation between the maths and the text.

OK, so back to the fine tuning as mentioned at the beginning of the document. A good example would be displaying the simple equation for the indefinite integral of y with respect to x:

\int y\, \mathrm{d}x

If you were to try this, you may write:

\[ \int y \mathrm{d}x \]

\int y \mathrm{d}x

However, this doesn't give the correct result. LaTeX doesn't respect the white-space left in the code to signify that the y and the dx are independent entities. Instead, it lumps them altogether. A \quad would clearly be overkill is this situation—what is needed are some small spaces to be utilized in this type of instance, and that's what LaTeX provides:

Command Description Size
\, small space 3/18 of a quad
\: medium space 4/18 of a quad
\; large space 5/18 of a quad
\! negative space -3/18 of a quad

NB you can use more than one command in a sequence to achieve a greater space if necessary.

So, to rectify the current problem:

\[ \int y\, \mathrm{d}x \]

\int y\, \mathrm{d}x

\[ \int y\: \mathrm{d}x \]

\int y\;\;\!\! \mathrm{d}x

\[ \int y\; \mathrm{d}x \]

\int y\; \mathrm{d}x

The negative space may seem like an odd thing to use, however, it wouldn't be there if it didn't have some use! Take the following example:

\[
  \left(
    \begin{array}{c}
      n \\
      r
    \end{array}
  \right) = \frac{n!}{r!(n-r)!
}
\
]

\left(
   \begin{matrix}
     n \\
     r
   \end{matrix}
   \right) = \frac{n!}{r!(n-r)!}


The matrix-like expression for representing binomial coefficients is too padded. There is too much space between the brackets and the actual contents within. This can easily be corrected by adding a few negative spaces after the left bracket and before the right bracket.

\[
  \left(\!
    \begin{array}{c}
      n \\
      r
    \end{array}
  \!\right) = \frac{n!}{r!(n-r)!
}
\
]

\left(\!
   \begin{matrix}
     n \\
     r
   \end{matrix}
   \!\right) = \frac{n!}{r!(n-r)!}

In any case, adding some spaces manually should be avoided whenever possible: it makes the source code more complex and it's against the basic principles of a What You See is What You Mean approach. The best thing to do is to define some commands using all the spaces you want and then, when you use your command, you don't have to add any other space. Later, if you change your mind about the length of the horizontal space, you can easily change it modifying only the command you defined before. Let us use an example: you want the d of a dx in an integral to be in roman font and a small space away from the rest. If you want to type an integral like \int x \; \mathrm{d} x, you can define a command like this:

\newcommand{\dd}{\; \mathrm{d}}

in the preamble of your document. We have chosen \dd just because it reminds the "d" it replaces and it is fast to type. Doing so, the code for your integral becomes \int x \dd x. Now, whenever you write an integral, you just have to use the \dd instead of the "d", and all your integrals will have the same style. If you change your mind, you just have to change the definition in the preamble, and all your integrals will be changed accordingly.

Advanced Mathematics: AMS Math package[edit]

The AMS (American Mathematical Society) mathematics package is a powerful package that creates a higher layer of abstraction over mathematical LaTeX language; if you use it it will make your life easier. Some commands amsmath introduces will make other plain LaTeX commands obsolete: in order to keep consistency in the final output you'd better use amsmath commands whenever possible. If you do so, you will get an elegant output without worrying about alignment and other details, keeping your source code readable. If you want to use it, you have to add this in the preamble:

\usepackage{amsmath}

Introducing text and dots in formulas[edit]

amsmath defines also the \dots command, that is a generalization of the existing \ldots. You can use \dots in both text and math mode and LaTeX will replace it with three dots "…" but it will decide according to the context whether to put it on the bottom (like \ldots) or centered (like \cdots).

Dots[edit]

LaTeX gives you several commands to insert dots in your formulas. This can be particularly useful if you have to type big matrices omitting elements. First of all, here are the main dots-related commands LaTeX provides:

Code Output Comment
\dots \dots generic dots, to be used in text (outside formulas as well). It automatically manages whitespaces before and after itself according to the context, it's a higher level command.
\ldots \ldots the output is similar to the previous one, but there is no automatic whitespace management; it works at a lower level.
\cdots \cdots These dots are centered relative to the height of a letter. There is also the binary multiplication operator, \cdot, mentioned below.
\vdots \vdots vertical dots
\ddots \ddots diagonal dots
\iddots inverse diagonal dots (requires the mathdots package)
\hdotsfor{n} \ldots \ldots to be used in matrices, it creates a row of dots spanning n columns.

Instead of using \ldots and \cdots, you should use the semantically oriented commands. It make it possible to adapt your document to different conventions on the fly, in case (for example) you have to submit it to a publisher who insists on following house tradition in this respect. The default treatment for the various kinds follows American Mathematical Society conventions.

Code Output Comment
A_1,A_2,\dotsc, LaTeX Dotsc.png for "dots with commas"
A_1+\dotsb+A_N LaTeX Dotsb.png for "dots with binary operators/relations"
A_1 \dotsm A_N LaTeX Dotsm.png for "multiplication dots"
\int_a^b \dotsi LaTeX Dotsi.png for "dots with integrals"
A_1\dotso A_N LaTeX Dotso.png for "other dots" (none of the above)

List of Mathematical Symbols[edit]

All the pre-defined mathematical symbols from the \TeX\ package are listed below. More symbols are available from extra packages.

Relation Symbols
Symbol Script Symbol Script Symbol Script Symbol Script Symbol Script
\leq \leq \geq \geq \equiv\, \equiv \models \models \prec \prec
\succ \succ \sim \sim \perp \perp \preceq \preceq \succeq \succeq
\simeq \simeq \mid \mid \ll \ll \gg \gg \asymp \asymp
\parallel \parallel \subset \subset \supset \supset \approx \approx \bowtie \bowtie
\subseteq \subseteq \supseteq \supseteq \cong \cong \sqsubset \sqsubset \sqsupset \sqsupset
\neq\, \neq \smile \smile \sqsubseteq \sqsubseteq \sqsupseteq \sqsupseteq \doteq \doteq
\frown \frown \in \in \ni \ni \propto \propto =\, =
\vdash \vdash \dashv \dashv <\, < >\, >
Greek Letters
Symbol Script
\Alpha\, and \alpha\, \Alpha and \alpha
\Beta\, and \beta\, \Beta and \beta
\Gamma\, and \gamma\, \Gamma and \gamma
\Delta\, and \delta\, \Delta and \delta
\Epsilon\,, \epsilon\, and \varepsilon \Epsilon, \epsilon and \varepsilon
\Zeta\, and \zeta\, \Zeta and \zeta
\Eta\, and \eta\, \Eta and \eta
\Theta\,, \theta\, and \vartheta \Theta, \theta and \vartheta
\Iota\, and \iota\, \Iota and \iota
\Kappa\, and \kappa\, \Kappa and \kappa
\Lambda\, and \lambda\, \Lambda and \lambda
\Mu\, and \mu\, \Mu and \mu
\Nu\, and \nu\, \Nu and \nu
\Xi\, and \xi\, \Xi and \xi
\Pi\,, \pi\, and \varpi \Pi, \pi and \varpi
\Rho\,, \rho\, and \varrho \Rho, \rho and \varrho
\Sigma\,, \sigma\, and \varsigma \Sigma, \sigma and \varsigma
\Tau\, and \tau\, \Tau and \tau
\Upsilon\, and \upsilon\, \Upsilon and \upsilon
\Phi\,, \phi\,, and \varphi \Phi, \phi and \varphi
\Chi\, and \chi\, \Chi and \chi
\Psi\, and \psi\, \Psi and \psi
\Omega\, and \omega\, \Omega and \omega
Binary Operations
Symbol Script Symbol Script Symbol Script Symbol Script
\pm\, \pm \cap\, \cap \diamond \diamond \oplus \oplus
\mp \mp \cup \cup \bigtriangleup \bigtriangleup \ominus \ominus
\times\, \times \uplus \uplus \bigtriangledown \bigtriangledown \otimes \otimes
\div \div \sqcap \sqcap \triangleleft \triangleleft \oslash \oslash
\ast \ast \sqcup \sqcup \triangleright \triangleright \odot \odot
\star \star \vee \vee \bigcirc \bigcirc \circ \circ
\wedge \wedge \dagger\, \dagger \bullet \bullet \setminus\, \setminus
\ddagger\, \ddagger \cdot \cdot \wr \wr \amalg \amalg
Set and/or Logic Notation
Symbol Script
\exists\, \exists
\forall\, \forall
\neg\, \neg
\in\, and \notin\, \in and \notin
\ni\, \ni
\land\, \land
\lor\, \lor
\rightarrow\, \rightarrow
\implies\, \implies
\iff\, \iff
\top\, \top
\bot\, \bot
\emptyset\, and \varnothing\, \emptyset and \varnothing
Delimiters
Symbol Script
\uparrow\, \uparrow
\Uparrow\, \Uparrow
\downarrow\, \downarrow
\Downarrow\, \Downarrow
\{\, \{
\}\, \}
\lceil\, \lceil
\rceil\, \rceil
\langle\, \langle
\rangle\, \rangle
/\, /
\backslash\, \backslash
|\, |
\|\, \|
Other symbols
Symbol Script
\partial \partial
\infty \infty
\nabla \nabla
\hbar \hbar
\Box \Box
\aleph \aleph
\ell \ell
\imath \imath
\jmath \jmath
\Re \Re
\Im \Im


Trigonometric Functions
Symbol Script Symbol Script Symbol Script Symbol Script
\sin \sin \cos \cos \tan \tan \cot \cot
\arcsin \arcsin \arccos \arccos \arctan \arctan \arccot \arccot
\sinh \sinh \cosh \conh \tanh \tanh \coth \coth
\sec \sec \csc \csc


Summary[edit]

As you begin to see, typesetting math can be tricky at times. However, because Latex provides so much control, you can get professional quality mathematics typesetting with relatively little effort (once you've had a bit of practice, of course!). It would be possible to keep going and going with math topics because it seems potentially limitless. However, with this tutorial, you should be able to get along sufficiently.

Clipboard

To do:

  • introduce symbols from [1]
  • add symbols from [2]
  • consider adding symbols from [3] -- the list of nearly all symbols available for LaTeX
  • Consider, instead of using the symbols from the above mentioned, using what has already been introduced in [4] instead of retyping the tables
  • How to box an equation within an align environment
  • Color in equations

Notes[edit]

  1. a b c d e f g h i j k l m n o p q r s t requires the amsmath package
  2. http://hdl.handle.net/2268/6219
  3. a b c d e f requires the mathtools package
  4. a b requires amsfonts or amssymb packages
  5. require mathrsfs package

Further reading[edit]

External links[edit]


Previous: Page Layout Index Next: Advanced Mathematics