Sunteți pe pagina 1din 16

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 1

LaTeX/Mathematics
One of the greatestmotivatingforces for DonaldKnuth when he began developingthe originalTeX systemwas to create somethingthat allowedsimpleconstructionof mathematicalformulas, whilst looking professionalwhen printed. The fact that he succeededwas most probablywhyTeX (and later on, LaTeX) became so popular within the scientific community Typesettingmathematicsis one of LaTeX's greateststrengths It is also a large topic due to the existenceof . . so much mathematicalnotation. If your documentrequiresonly a few simplemathematicalformulas, plain LaTeX has most of the tools that you will
[1] need. If you are writing a scientificdocumentthat containsnumerouscomplicatedformulas, the amsmathpackage introducesseveral new commandsthat are more powerfuland flexible than the ones providedby LaTeX. The , mathtoolspackagefixes some amsmathquirks and adds some useful settings, symbols and environmentsto amsmath. [2] LaTeX

To use either package include: ,

\usepackageamsmath { }

or

\usepackagemathtools { }

in the preambleof the document. The mathtoolspackageloads the amsmathpackageand hence there is no need to \usepackage {amsmath} in the preambleif mathtoolsis used.

Mathematics environments
LaTeX needsto know beforehandthat the subsequenttext does in fact contain mathematicalelements. This is because LaTeX typesetsmaths notationdifferentlythan normal text. Therefore, special environmentshave been declared for this purpose. Theycan be distinguishedinto two categoriesdependingon how theyare presented : text - text formulasare displayedin-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- displayedformulasare separatefrom the main text. As maths require special environments there are naturallythe appropriateenvironmentnames you can use in the , standard way. Unlike most other environments however, there are some handy shorthandsto declaringyour formulas. , The followingtable summarizesthem: Type Text Displayed Environment \begin{math}...\end{math} \begin{displaymath }...\end{displaymath or } \begin{equation *}...\end{equation *}
[3]

LaTeX shorthand \(...\) \[...\]

TeX shorthand $...$ $$...$$

Note: Usingthe $$...$$ shouldbe avoided, as it maycause problems, particularlywith the AMS-LaTeX macros. Furthermore shoulda problemoccur, the error messagesmaynot be helpful. , Additionally there is a secondpossibleenvironmentfor the displayedtypeof formulas: equation The difference , . betweenthis and displaymathis that equation also adds sequentialequation numbersby the side. If you are typingtext normally you are said to be in text mode, while you are typingwithin one of those mathematical , environments you are said to be in math mode, that has some differencescomparedto the text mode: , 1. Most spacesand line breaksdo not have any significance as all spacesare either derivedlogicallyfrom the , mathematicalexpressions or have to be specifiedwith special commandssuch as \quad ,

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world 2. Emptylines are not allowed. Only one paragraphper formula. 3. Each letter is consideredto be the name of a variableand 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 .
Getting Started 1. Introduction 2. Basics 3. Errors and Warnings Formatting 1. Document Structure 2. Useful Measurement Macros 3. Text Formatting 4. ParagraphFormatting 5. Colors 6. Fonts 7. List Structures 8. Tables 9. Title creation 10. Page Layout 11. Importing Graphics 12. Floats, Figures and Captions 13. Footnotes and Margin Notes 14. Hyperlinks 15. Labels and Crossreferencing Creating Graphics 1. 2. 3. 4. 5. Creating Graphics Picture PGF/TikZ PSTricks Xy-pic

Page 2

Inserting "Displayed" maths inside blocks of text


In order for some operators, such as \lim or \sum to be displayedcorrectlyinside some math environments(read $ . ......$), it might be convenientto write the \displaystyleclass inside the environment Doing so might cause the line to be taller, but will cause exponentsand indices to be displayedcorrectlyfor some math operators. For example, the $\sum$ will print a smaller and $\displaystyle \sum$ will print a biggerone , like in equations(This only works with AMSMATHpackage ).

Symbols
Mathematicshas lots and lots of symbols If there is one aspect of maths that is difficultin LaTeX it is tryingto ! rememberhow to producethem. There are of coursea set of symbolsthat can be accesseddirectly from the keyboard :
+ -= !/( ) [ ] < > | ':

Beyondthose listed above, distinct commandsmust be issued in order to displaythe desired symbols Andthere are a . lot! of Greek letters, set and relations symbols arrows, binaryoperators, etc. For example: ,

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

TechnicalTexts

Fortunately there's a tool that can greatlysimplifythe search for the commandfor a specific symbol. Look for , "Detexify" in the externallinks section below. Anotheroption would be to look in the "The ComprehensiveLaTeX SymbolList" in the externallinks section below.

1. 2. 3. 4. 5.

Greek letters

Mathematics AdvancedMathematics Theorems ChemicalGraphics Algorithmsand Pseudocode 6. Linguistics

Greek letters are commonlyused in mathematics and theyare very easy to typein math mode. You just have to typethe Special Pages , name of the letter after a backslash if the first letter is lowercase you will get a lowercaseGreek letter, if the first letter : , 1. Indexing is uppercase(and only the first letter), then you will get an uppercaseletter. Note that some uppercaseGreek letters look 2. Glossary like Latin ones, so theyare not providedby LaTeX (e.g. uppercaseAlpha and Beta are just "A" and "B" respectively ). 3. BibliographyManagement 4. More Bibliographies Lowercaseepsilon, theta, phi, pi, rho, and sigma are providedin two different versions The alternate, or variant, version . is created by adding "var" before the name of the letter:
Special Documents 1. Letters 2. Presentations 3. Teacher's Corner AdvancedTopics 1. 2. 3. 4. 5. 6. 7. 8. 9. General Guidelines CustomizingLaTeX Packages AdvancedTopics CollaborativeWriting of LaTeX Documents Export To Other Formats Internationalization Accents and Special Characters Tips / Tricks

\[ \alpha, \Alpha, \beta, \Beta, \gamma, \Gamma, \pi, \Pi, \phi, \varphi, \Phi \]

Scroll down to #List of MathematicalSymbolsfor a completelist of Greek symbols .

Operators
An operatoris a functionthat is written as a word: e.g. trigonometricfunctions(sin, cos, tan), logarithmsand exponentials(log, exp). LaTeX has manyof these definedas commands :

Appendices

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

For certain operatorssuch as limits, the subscriptis placed underneaththe operator :

1. 2. 3. 4. 5. 6. 7. 8.

Authors Useful Links Installation InstallingExtra Packages Package Reference Sample LaTeX documents Index Command Glossary

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 3

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

edit this box (https://secure.wikimedia.org/ wikibooks/en/wiki/index.php? title= Template:LaTeX/Top&action= edit) edit the TOC (https://secure.wikimedia.org/ wikibooks/en/wiki/index.php? title= Template:LaTeX/ Contents&action= edit)

For the modularoperatorthere are two commands \bmod and \pmod: :

\[ a \bmod b \]

\[ x \equiv a \pmod b \]

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

Powers and indices


Powersand indices are equivalentto superscriptsand subscriptsin normal text mode. The caret (^) characteris used to raise something and the , underscore(_) is for lowering. If more than one expressionis raised or lowered, theyshouldbe groupedusing curlybraces ({ and }).

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

An underscore(_) can be used with a verticalbar ( ) to denoteevaluationusing subscriptnotationin mathematics :

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

Fractions and Binomials


A fraction is created using the \frac{numerator }{denominator command. (for those who need their memoriesrefreshed, that's the top and bottom } respectively Likewise the binomialcoefficient(aka the Choosefunction maybe written using the \binom command[3]: !). , )

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

It is also possibleto use the \choose commandwithout the amsmathpackage :

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

You can embedfractionswithin fractions:

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 4

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

Note that when appearinginside anotherfraction, or in inline text , a fraction is noticeablysmaller than in displayedmathematics The \tfrac and .
[3] . \dfrac commands force the use of the respectivestyles, \textstyleand \displaystyle Similarly, the \tbinom and \dbinom commands typeset the binomialcoefficient .

Anotherway to write fractionsis to use the \over commandwithout the amsmathpackage :

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

For relativelysimplefractions, it maybe more aestheticallypleasingto use powers and indices:

\[ ^3/_7 \]

If you use them throughoutthe document, usageof xfrac packageis recommended This packageprovides \sfrac commandto 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 \]

Alternatively the nicefrac packageprovidesthe \nicefrac command, whose usageis similar to \sfrac. ,

Continued fractions
Continuedfractionsshouldbe written using \cfrac command[3]:

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

Multiplication of two numbers


To make multiplicationvisuallysimilar to a fraction, a nested arraycan be used, for example multiplicationof numberswritten one below the other.

\begin{equation } \frac{ \begin{array}[b]{r} \left( x_1 x_2 \right)\\ https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes 30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world \end{equation }

Page 5

Roots
The \sqrt commandcreates a squareroot surroundingan expression It accepts an optionalargumentspecifiedin squarebrackets([ and ]) to change . magnitude :

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

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

Somepeopleprefer writing the squareroot "closing" it over its content. This methodarguablymakes it more clear what is in the scopeof the root sign. This habit is not normallyused while writing with the computer, but if you still want to change the output of the squareroot, LaTeX gives you this possibility Just add the followingcode in the preambleof 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 renamesthe \sqrt commandas \oldsqrt then redefines\sqrt in terms of the old one, adding somethingmore. The new square , root can be seen in the picture on the left, comparedto the old one on the right. Unfortunatelythis code won't work if you want to use multipleroots: if you try to write as \sqrt[b]{a} after you used the code above, you'll just get a wrongoutput. In other words, you can redefinethe squareroot this way only if you are not goingto use multipleroots in the whole document. An alternativepiece of TeX code that does allow multipleroots is

\LetLtxMacro {\oldsqrt }{\sqrt} % makes all sqrts closed \renewcommand {\sqrt}[1][]{% \def\DHLindex {#1}\mathpalette \DHLhksqrt } \def\DHLhksqrt #1#2{% \setbox0=\hbox{$#1\oldsqrt [\DHLindex ]{#2\,}$}\dimen0=\ht0 \advance \dimen0-0.2\ht0 \setbox2=\hbox{\vrule height\ht0 depth -\dimen0}% {\box0\lower0.71pt\box2}} $\sqrt[a]{b} \quad \oldsqrt [a]{b}$

Howeverthis requiresthe \usepackage {letltxmacro package }

Sums and integrals


The \sum and \int commandsinsert the sum and integral symbolsrespectively with limits specifiedusing the caret (^) and underscore(_). The typical , notationfor sums is:

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 6

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

The limits for the integralsfollowthe same notation. It's also importantto representthe integrationvariableswith an upright d, which in math mode is obtained throughthe \mathrm{} command, and with a small space separatingit from the integrand which is attainedwith the \, command. ,

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

There are manyother "big" commandswhich operate in a similar manner:


\sum \bigoplus \bigcup \bigsqcup \int \prod \bigotimes \bigcap \bigvee \oint \coprod \bigodot \biguplus \bigwedge [3] \iint [3] \idotsint

[3] \iiint

[3] \iiiint

For more integral symbols includingthose not included by default in the ComputerModernfont, try the esint package , . The \substack command[3] allowsthe use of \\ to write the limits over multiplelines:

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

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

\[ \int\limits_a^b \]

Howeverif you want this to applyto ALLintegrals, it is preferableto specifythe intlimitsoption when loadingthe amsmathpackage :

\usepackage [intlimits ]{amsmath }

Subscriptsand superscriptsin other contextsas well as other parametersto amsmathpackagerelated to them are describedin AdvancedMathematics chapter. For biggerintegrals, you mayuse personal declarations or the bigintspackage [4]. ,

Brackets, braces and delimiters


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

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 7

The use of delimiterssuch as bracketssoon becomesimportantwhen dealingwith anythingbut the most trivial equations Withoutthem, formulascan . become ambiguous Also, special types of mathematicalstructures such as matrices, typicallyrely on delimitersto enclosethem. . , There are a varietyof delimitersavailablefor use in LaTeX:

\[ ( a ), [ b ], \{ c \}, | d |, \| e \|, \langle f \rangle, \lfloor g \rfloor, \lceil h \rceil \]

Automatic sizing
Very often mathematicalfeatureswill differ in size, in which case the delimiterssurroundingthe expressionshouldvary accordingly This can be done . automaticallyusing the \left and \right commands Anyof the previousdelimitersmaybe used in combinationwith these: .

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

Curlybraces are defineddifferentlyby using \left\{ and \right\},

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

If a delimiteron only one side of an expressionis required then an invisibledelimiteron the other side maybe denotedusing a period (.). ,

\[ \left.\frac{x^3}{3}\right|_0^1 \]

Manual sizing
In certain cases, the sizingproducedby the \left and \right commandsmaynot be desirable, or you maysimplywant finer control over the delimiter sizes. In this case, the \big, \Big, \bigg and \Bigg modifier commandsmaybe used:

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

Matrices and arrays


[3] A basic matrix maybe created using the matrix environment : in commonwith other table-like structures entriesare specifiedby row, with columns , separatedusing an ampersand(&) and a new rows separatedwith a double backslash(\\)

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 8

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

To specifyalignmentof columns in the table, use starred version[5]:

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

The alignmentby default is c but it can be any columntypevalid in array environment . Howevermatrices are usuallyenclosedin delimitersof some kind, and while it is possibleto use the \left and \right commands there are variousother , predefinedenvironmentswhich automaticallyinclude delimiters : Environmentname Surroundingdelimiter pmatrix
[3] [5]

Notes centers columns by default allowsto specifyalignmentof columns in optionalparameter centers columns by default allowsto specifyalignmentof columns in optionalparameter centers columns by default allowsto specifyalignmentof columns in optionalparameter centers columns by default allowsto specifyalignmentof columns in optionalparameter centers columns by default allowsto specifyalignmentof colums in optionalparameter

pmatrix * bmatrix

[3] [5]

bmatrix * Bmatrix

[3] [5]

Bmatrix * vmatrix

[3] [5]

vmatrix * Vmatrix

[3] [5]

Vmatrix *

When writing down arbitrarysized matrices, it is commonto use horizontal, verticaland diagonaltriplets of dots (known as ellipses) to fill in certain columns and rows. These can be specifiedusing 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 } \]

In some cases you maywant to have finer control of the alignmentwithin each column, or want to insert lines betweencolumns or rows. This can be achievedusing the array environment which is essentiallya math-mode versionof the tabular environment which requiresthat the columns be pre, , specified:

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world 3 & 4 \end{array} \]

Page 9

You maysee that the AMS matrix class of environmentsdoesn't leave enoughspace when used togetherwith fractionsresultingin output similar to this:

To counteractthis problem add additionalleadingspace with the optionalparameterto 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 } \]

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

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

Matrices in running text


To insert a small matrix, and not increaseleadingin the line containingit, use smallmatrixenvironment :

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.

Adding text to equations


The math environmentdiffersfrom the text environmentin the representationof text. Here is an example of tryingto representtext within the math environment :

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

There are two noticeableproblems: there are no spacesbetweenwords or numbers, and the letters are italicizedand more spaced out than normal. Both issues are simplyartifactsof the maths mode, in that it treats it as a mathematicalexpression spacesare ignored (LaTeX spacesmathematicsaccordingto : its own rules), and each characteris a separateelement(so are not positionedas closely as normal text). There are a number of waysthat text can be added properly The typical way is to wrap the text with the \text{...} command [3] (a similar command . is \mbox{...}, thoughthis causesproblemswith subscripts and has a less descriptivename). Let's see what happenswhen the above equation code is , adapted:

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 10

The text looks better. However there are no gaps betweenthe numbersand the words. Unfortunately you are requiredto explicitlyadd these. There are , , manywaysto add spacesbetweenmaths elements, but for the sake of simplicityyou mayliterallyadd the space characterin the affected \text(s) itself (just before the text.)

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

Formatted text
Usingthe \text is fine and gets the basic result. Yet, there is an alternativethat offers a little more flexibility You mayrecall the introductionof font . formattingcommands such as \textrm, \textit, \textbf, etc. These commandsformatthe argumentaccordingly e.g., \textbf{bold text} , , gives bold text. These commandsare equallyvalid within a maths environmentto include text. The added benefit here is that you can have better control over the font formatting rather than the standard text achievedwith \text. ,

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

Formatting mathematics symbols


We can now formattext; what about formattingmathematicalexpressions There are a set of formattingcommandsvery similar to the font formatting ? ones just used, except that theyare specificallyaimed at text in math mode (requires amsfonts ) LaTeXcommand \mathnormal {} \mathrm{} \mathit{} \mathbf{} \mathsf{} \mathtt{} ABCDEFabcdef 123456 Sample Description Commonuse

the default math most mathematicalnotation font this is the default or normal font, units of measurement one word functions , unitalicised italicisedfont bold font Sans-serif Monospace (fixed-width) font Calligraphy (uppercaseonly) often used for sheaves/schemes and categories, used to denotecryptologicalconceptslike an alphabetof definition( ), message space( ), ciphertextspace ( ) and key space( ); Kleene's ; naming conventionin descriptionlogic Almostcanonicalfont for Lie algebras with , superscriptused to denoteNew Testamentpapyri, ideals in ring theory Used to denotespecial sets (e.g. real numbers) An alternativefont for categoriesand sheaves. vectors

\mathcal {}

\mathfrak {} \mathbb{}
[6]

[6]

Fraktur Blackboardbold Script

\mathscr {}

[7]

The maths formattingcommandscan be wrappedaroundthe entire equation, and not just on the textual elements: theyonly formatletters, numbers, and uppercaseGreek, and the rest of the maths syntaxis ignored. To bold lowercaseGreek or other symbolsuse the \boldsymbolcommand[3]; this will only work if there existsa bold versionof the symbolin the current font. As a last resortthere is the \pmb command[3] (poor mans bold): this printsmultipleversionsof the characterslightlyoffsetagainst each other

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 11

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

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

Accents
So what to do when you run out of symbolsand fonts? Well the next step is to use accents:
a' \hat{a} \grave{a} \dot{a} \not{a} \overrightarrow {AB} a''' \overline {aaa} \breve{a} [3] \dddot{a} \widehat{AAA} \tilde{a} a'' \bar{a} \acute{a} \ddot{a} \mathring {a} \overleftarrow {AB} a'''' \check{a} \vec{a} [3] \ddddot {a} \widetilde{AAA}

Plus and minus signs


Latexdeals with the + and signsin two possibleways. The most commonis as a binaryoperator When two maths elementsappeareither side of the . sign, it is assumedto be a binaryoperator and as such, allocatessome space either side of the sign. The alternativeway is a sign designation This is when , . you state whethera mathematicalquantityis either positiveor negative. This is commonfor the latter, as in maths, such elementsare assumedto be positiveunless a is prefixedto it. In this instance, you want the sign to appearclose to the appropriateelementto show their association. If you put a + or a with nothing before it but you want it to be handledlike a binaryoperatoryou can add an invisible characterbefore the operatorusing {}. 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 invisiblecharacterwhere necessary . A plus-minus sign used for uncertaintyis written as:

\[ \pm \]

Controlling horizontal spacing


LaTeX is obviouslypretty good at typesettingmathit was one of the chief aims of the core Tex systemthat LaTeX extends. However it can't alwaysbe , relied upon to accuratelyinterpret formulasin the way you did. It has to make certain assumptionswhen there are ambiguousexpressions The result . tends to be slightlyincorrecthorizontalspacing. In these events, the output is still satisfactory yet any perfectionistswill no doubtwish to fine-tune their , formulasto ensurespacing is correct. These are generallyvery subtle adjustments . There are other occasionswhere LaTeX has done its job correctly, but you just want to add some space, maybeto add a commentof some kind. For example, in the followingequation, it is preferableto ensurethere is a decent amountof space betweenthe math 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. \]

This code produceserrors with Miktex 2.9 and does not yield the resultsseen on the right. Use \textrm instead of just \text.

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 12

(Note that this particularexample can be expressedin more elegant code by the cases constructprovidedby the amsmathpackagedescribedin AdvancedMathematicschapter.) LaTeX has definedtwo commandsthat can be used anywherein documents(not just maths) to insert some horizontalspace. Theyare \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 providedby \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 separationbetween the maths and the text. OK, so back to the fine tuning as mentionedat the beginningof the document. A good example would be displayingthe simpleequation for the indefinite integral of y with respect to x:

If you were to try this, you maywrite:

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

However this doesn't givethe correct result. LaTeX doesn't respect the white-space left in the code to signifythat the y and the dx are independent , entities. Instead, it lumps them altogether A \quad would clearly be overkillis this situationwhat is needed are some small spacesto be utilizedin this . typeof instance, and that's what LaTeX provides: Command Description \, \: \; \! small space large space Size 3/18 of a quad 5/18 of a quad

mediumspace 4/18 of a quad negative space -3/18 of a quad

NB you can use more than one commandin a sequenceto achieve a greaterspace if necessary . So, to rectifythe current problem :

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

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

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

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

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world

Page 13

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

The matrix-like expressionfor representingbinomialcoefficientsis too padded. There is too much space betweenthe bracketsand the actual contents within. This can easily be correctedby adding a few negative spacesafter the left bracket and before the right bracket.

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

In any case, adding some spacesmanuallyshouldbe avoidedwheneverpossible it makes the sourcecode more complex and it's against the basic : principlesof a What You See is What You Meanapproach The best thing to do is to define some commandsusing all the spacesyou 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 horizontalspace, you can easily change it modifyingonly the commandyou definedbefore. 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 typean integral like \int x \; \mathrm{d} x, you can define a commandlike this:

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

in the preambleof your document. We have chosen \dd just becauseit remindsthe "d" it replacesand it is fast to type. Doing so, the code for your integral becomes \int x \dd x. Now, wheneveryou write an integral, you just have to use the \dd instead of the "d", and all your integralswill have the same style. If you change your mind, you just have to change the definitionin the preamble, and all your integralswill be changedaccordingly .

Advanced Mathematics: AMS Math package


The AMS (AmericanMathematicalSociety) mathematicspackageis a powerfulpackagethat creates a higher layer of abstractionover mathematical LaTeX language if you use it it will make your life easier. Somecommandsamsmathintroduceswill make other plain LaTeX commandsobsolete in ; : order to keep consistencyin the final output you'd better use amsmathcommandswheneverpossible If you do so, you will get an elegant output without . worryingabout alignmentand other details, keepingyour sourcecode readable. If you want to use it, you have to add this in the preamble:

\usepackage {amsmath }

Introducing text and dots in formulas


amsmathdefines also the \dots command, that is a generalizationof 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 accordingto the context whetherto put it on the bottom (like \ldots) or centered (like \cdots).

Dots
LaTeX gives you several commandsto insert dots in your formulae. This can be particularlyuseful if you have to typebig matrices omitting elements. First of all, here are the main dots-related commandsLaTeX provides: Code \dots \ldots \cdots Output Comment genericdots, to be used in text (outside formulaeas well). It automaticallymanageswhitespacesbefore and after itself accordingto the context, it's a higher level command. the output is similar to the previousone, but there is no automaticwhitespacemanagement it works at a lowerlevel. ; These dots are centered relativeto the height of a letter. There is also the binarymultiplicationoperator \cdot, mentioned , 30-05-2012 15:29:43

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

LaTeX/Mathematics - Wikibooks, open books for an open world \iddots \hdotsfor {n} inverse diagonaldots (requiresthe mathdotspackage ) to be used in matrices, it creates a row of dots spanningn columns.

Page 14

Instead of using \ldots and \cdots, you shoulduse the semanticallyorientedcommands It makes it possibleto adapt your documentto different . conventionson the fly, in case (for example) you have to submit it to a publisherwho insists on followinghouse tradition in this respect. The default treatmentfor the variouskinds followsAmericanMathematicalSocietyconventions . Code A_1,A_2,\dotsc, A_1+\dotsb+A_N A_1 \dotsm A_N \int_a^b \dotsi A_1\dotso A_N Output Comment for "dots with commas " for "dots with binaryoperators/relations" for "multiplicationdots" for "dots with integrals" for "other dots" (none of the above)

List of Mathematical Symbols


All the pre-definedmathematicalsymbolsfrom the \TeX\ packageare listed below. More symbolsare availablefrom extra packages . RelationSymbols Symbol Script
\equiv \perp \ll \supset \cong \sqsubseteq \ni <

Symbol Script
\leq \succ \simeq \parallel \subseteq \neq \frown \vdash

Symbol Script
\geq \sim \mid \subset \supseteq \smile \in \dashv

Symbol

Script
\models \preceq \gg \approx \sqsubset \sqsupseteq \notin >

Symbol Script
\prec \succeq \asymp \bowtie \sqsupset \doteq \propto =

Symbol Script
\pm \mp \times \div \ast \star \dagger \ddagger

Binary Operations Symbol Script Symbol Script


\cap \cup \uplus \sqcap \sqcup \vee \wedge \cdot \diamond \bigtriangleup \bigtriangledown \triangleleft \triangleright \bigcirc \bullet \wr

Symbol Script
\oplus \ominus \otimes \oslash \odot \circ \setminus \amalg

Symbol Script
\exists \nexists \forall \neg \in \notin \ni \land \lor

Set and/or Logic Notation Symbol Script


\rightarrow \implies

) \Rightarrow (preferredfor implication


\leftrightarrow \iff \Leftrightarrow(preferredfor equivalence(iff)) \top \bot

and

\emptyset and \varnothing

Symbol

Script

Symbol

Delimiters Script Symbol Script

Symbol

Script 30-05-2012 15:29:43

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

LaTeX/Mathematics - Wikibooks, open books for an open world


\downarrow \Downarrow \lfloor \rfloor

Page 15

Symbol and and and and , and and and , and and and and and

Script
\Alpha and \alpha \Beta and \beta \Gamma and \gamma \Delta and \delta

GreekLetters Symbol and and and , , , and and and and and , , and and and and

Script
\Nu and \nu \Xi and \xi \Omicron and \omicron \Pi, \pi and \varpi \Rho, \rho and \varrho \Sigma, \sigma and \varsigma \Tau and \tau \Upsilon and \upsilon \Phi, \phi and \varphi \Chi and \chi \Psi and \psi \Omega and \omega

\Epsilon, \epsilon and \varepsilon \Zeta and \zeta \Eta and \eta \Theta, \theta and \vartheta \Iota and \iota \Kappa and \kappa \Lambda and \lambda \Mu and \mu

Symbol Script
\partial \eth \hbar

Symbol Script
\imath \jmath \ell

Other symbols Symbol Script Symbol Script


\Re \Im \wp \nabla \Box \infty

Symbol Script
\aleph \beth \gimel

Symbol Script
\sin \cos \tan \cot

TrigonometricFunctions Symbol Script Symbol Script Symbol Script


\arcsin \arccos \arctan \arccot \sinh \cosh \tanh \coth \sec \csc

Summary
As you begin to see, typesettingmath can be tricky at times. However becauseLatexprovidesso much control, you can get professionalquality , mathematicstypesettingwith relativelylittle effort (once you've had a bit of practice, of course!). It would be possibleto keep goingand goingwith math topics becauseit seems potentiallylimitless. However with this tutorial, you shouldbe able to get along sufficiently , .

Notes
1. 2. 3. 4. 5. 6. 7. http://www.ams.org/publications /authors/tex/amslatex http://www.tex.ac.uk/ctan/macros/latex/contrib/mh/mathtools.pdf a b c d e f g h i j k l m n o p q r s t requiresthe amsmathpackage http://hdl.handle.net/2268/6219 a b c d e f requiresthe mathtoolspackage a b requires amsfonts or amssymb packages require mathrsfs package

Further reading
meta:Help:Displayinga formula: Wikimediauses a subset of LaTeX commands .

External links
LaTeX maths symbols(http://www.artofproblemsolving .com/Wiki/index.php/LaTeX:Symbols) detexify(http://detexify .kirelabs.org) : applet for looking up LaTeX symbolsby handwritingthem .com/viewer?url=ftp://ftp.ams.org/pub/tex/doc/amsmath/amsldoc .pdf) amsmath documentation(https://docs.google LaTeX - The Student Room (http://www.thestudentroom .co.uk/wiki/LaTeX)

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

LaTeX/Mathematics - Wikibooks, open books for an open world The ComprehensiveLaTeX SymbolList (https://docs.google .com/viewer?url=http://www.ctan.org/tex-archive/info/symbols /comprehensive / symbols -letter.pdf)

Page 16

Retrievedfrom "http://en.wikibooks .org/w/index.php?title=LaTeX/Mathematics oldid=2356545" & This page was last modifiedon 28 May 2012, at 12:04. Text is availableunderthe Creative CommonsAttribution -ShareAlikeLicense; additionalterms mayapply. See Terms of Use for details.

https://secure.wikimedia.org/wikibooks/en/w/index.php?title=LaTeX/Mathematics&printable=yes

30-05-2012 15:29:43

S-ar putea să vă placă și