User:Clebell/Sandbox

Sandbox Document
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 (discuss • contribs) 15:24, 6 March 2011 (UTC)

Mathematical typesetting is one of LaTeX's greatest strengths.

Math Packages
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
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:

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:. The difference between this and is that  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
 * 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
In order for some operators, such as or  to be displayed correctly inside some math environments (read ), it might be convenient to write the  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
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:

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
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:

Operators
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:

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

For the modular operator there are two commands: and :

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

Powers and indices
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  ).

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

Fractions and Binomials
A fraction is created using the 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 command :

It is also possible to use the command without the  package:

You can embed fractions within fractions:

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

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

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

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

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

Continued fractions
Continued fractions should be written using command :

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

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:

This TeX code first renames the command as, then redefines  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 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
The and  commands insert the sum and integral symbols respectively, with limits specified using the caret  and underscore :

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

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

The command allows the use of  to write the limits over multiple lines:

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

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

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

For bigger integrals, you may use personal declarations, or the package.

Brackets, braces and delimiters
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:

Automatic sizing
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 and  commands. Any of the previous delimiters may be used in combination with these:

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
In certain cases, the sizing produced by the and  commands may not be desirable, or you may simply want finer control over the delimiter sizes. In this case, the, , and  modifier commands may be used:

Matrices and arrays
A basic matrix may be created using the environment : 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

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

The alignment by default is but it can be any column type valid in  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:

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, and  respectively:

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 environment, which is essentially a math-mode version of the tabular environment, which requires that the columns be pre-specified:

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:

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

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

Adding text to equations
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:

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 command (a similar command is, though this causes problems with subscripts, and has a less descriptive name). Let's see what happens when the above equation code is adapted:

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 (s) itself (just before the text.)

Formatted text
Using the 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, , , etc. These commands format the argument accordingly, e.g., 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.

Formatting mathematics symbols
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 ) 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 command ; this will only work if there exists a bold version of the symbol in the current font. As a last resort there is the command (poor mans bold): this prints multiple versions of the character slightly offset against each other

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

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

Plus and minus signs
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
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.

{{LaTeX/Example|code= \[ 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} $$ }}
 * render=

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 construct provided by the  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 and

A is a space equal to the current font size. So, if you are using an 11pt font, then the space provided by will also be 11pt (horizontally, of course.) The  gives twice that amount. As you can see from the code from the above example, s 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:

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 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:

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

So, to rectify the current problem:

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:

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.

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, you can define a command like this:

in the preamble of your document. We have chosen just because it reminds the "d" it replaces and it is fast to type. Doing so, the code for your integral becomes. Now, whenever you write an integral, you just have to use the 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
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 introduces will make other plain LaTeX commands obsolete: in order to keep consistency in the final output you'd better use  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:

Introducing text and dots in formulas
defines also the command, that is a generalization of the existing. You can use 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 ) or centered (like ).

Dots
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:

Instead of using and, 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.

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

Summary
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.