Introduction to Mathematica®


Sample 2-D graphic produced with Mathematica Sample 3-D graphic produced with Mathematica

Left: Mathematica 2-D plot of empirical failure CDF for ball-bearing data, versus fitted Weibull distribution
Right: Mathematica 3-D plot of Equation for righthand plot

Mathematica is a registered trademark of  Wolfram Research Inc.


Introduction to Mathematica

Mathematica is a versatile, powerful application package for doing mathematics and publishing mathematical results. It runs on most popular workstation operating systems, including Microsoft Windows, Apple Macintosh OS, Linux, and other Unix-based systems.

Mathematica is used by scientists and engineers in disciplines ranging from astronomy to zoology; typical applications include computational number theory, ecosystem modeling, financial derivatives pricing, quantum computation, statistical analysis, and hundreds more. (See the links below for ways of finding applications and sample code.)

The best way to understand Mathematica is to see it in action. The sections below describe three major categories of usage:

  • As an end user tool: Mathematica can be used to perform computations, either numeric or symbolic. Results can be visualized using 2-D and 3-D graphics.

  • As a programming tool: Mathematica provides a rich set of programming extensions to its end-user language. Programming can be done in procedural, functional, or logic (rule-based) style, or a mixture of all three. For tasks requiring interfaces to the external environment (such as extraction from a relational database) Mathematica provides MathLink, which allows Mathematica programs to communicate with external programs written in C, Java, or other languages.

  • As a publishing tool: Mathematica has extensive capabilities for formatting graphics, text, and equations. Documents, called notebooks, can be exported as PostScript, TeX, HTML, or a combination of HTML and MathML (Mathematical Markup Language).

These uses are illustrated in the sections that follow. No prior familiarity with Mathematica is assumed.


Interactive Mathematica sessions

In the examples below, corresponding to what would be seen in an actual Mathematica session, user inputs are shown in Courier bold font, and Mathematica outputs are shown in Courier font. In the text, where user inputs are described, control keys are shown in Courier italic font.  For example, Esc-int-Esc. indicates the characters "int" bracketed by the escape key.

The screen image below shows a typical user session with Mathematica. It is possible to execute Mathematica in a text-only shell prompt or command window, but normally the user will be running the Mathematica graphical user interface on Microsoft Windows, Apple Macintosh, or under X Windows on a Unix system. These environments all provide windows that look similar to what is shown here.

Image showing windows in a Mathematica session

The window in the foreground is the Mathematica help browser. This has detailed information and examples for all available functions and options. It also contains demos, information on getting started with Mathematica, and an online version of The Mathematica Book, a complete 1200-page reference.

The window titled "MyNotebook.nb" is a notebook, the interactive interface to mathematica. Below the line "In[1]:=" is an input entered by the user. After entering input, hitting Shift-Enter  (Shift-Return  on a Macintosh), causes Mathematica to perform the computation and display "Out[1]=" followed by the result. Subsequent input-output lines will increment the index, e.g., "In[2]:=," etc. (The use of the index number is explained below.)

The user input shown here is in a style that only uses symbols that can be entered from the keyboard. Entry can also be made using traditional mathematical symbols, by clicking on the small palette window shown on the right. Additional palettes are available which provide all the symbols normally used in mathematics notation, plus characters from various alphabets such as Greek and Hebrew.

Symbols can also be entered using keyboard shortcuts; e.g., Esc-int-Esc  causes an integral sign to be typed. In general, anything that can be done in Mathematica using palettes and menus can also be done with keyboard shortcuts. For example, to cause Mathematica to simplify a subexpression on the input line, highlight the subexpression and key Ctrl-Shift-Enter  (or Command-Return  on a Macintosh).

When Mathematica is started, it opens an empty notebook labeled "Untitled". When a notebook is saved, it is given a title ("MyNotebook.nb" in this case). Any number of notebooks may be opened simultaneously, and each user typically creates his or her own library of notebooks representing current work. Notebooks can be shared, and a notebook sent by a colleague can be modified and sent back. Stored notebooks consist entirely of marked-up text, and are portable across all environments where Mathematica runs.


End-user computation

Mathematica can be used as a calculator, to do numeric computations:

In[1]:= ((0.04587*54.32497 + 4.59058433734947*^7)/48700043)^131.94564

Out[1]= 0.000411241

The keyboard characters used for input are fairly standard. "*^" is a special notation used to indicate a power of ten; e.g., 4.59058433734947*^7 means 4.59058433734947 x 107.

Mathematica supports a wide range of computations, for example, numeric integration:

In[2]:= Integrate[Sin[x]/(E^(0.43*x)*x), {x, 0, Infinity}]

Out[2]= 1.1647

Note that this could also have been entered, using the palette, in "traditional form":

Image of the integral done in the previous example

Mathematica also provides a wide range of symbolic computation, including differentiation, integration, and solution of algebraic and differential equations. For example, entering the integral from the above example without the limits of integration gives an expression for the indefinite integral:

In[3]:= Integrate[Sin[x]/(E^(0.43*x)*x), x]

Out[3]= (-(1/2))*I*(ExpIntegralEi[(-0.43 + I)*x] - ExpIntegralEi[(-0.43 - I)*x])

Another example, solving a 3rd degree polynomial:

In[4]:= p := x^3 - 6 x^2 + 11 x - 6

This input, which produces no output, assigns the polynomial expression to the variable p. The assignment is done because we will use this polynomial again later, so the assignment saves retyping it. Note the difference between the assignment operator := and the equality operator ==, which is used here to form the equation we are asking Mathematica to solve:

In[5]:= Solve[p == 0]

Out[5]= {{x -> 1}, {x -> 2}, {x -> 3}}

There are a couple of things to note in the output. Curly brackets represent lists. So, e.g., {1, 2, 3, 4} is a list of the integers 1-4; {{1, 2}, {3, 4}} is a list of two lists, etc. In the example above, Mathematica returns the roots of the polynomial as a list of substitution rules. This is done in order to provide the roots in a form that is useful in further computations. Recall that each output line has an index n; the contents of an output can be referenced in a later computation as %n. So, using the operator /., which applies a rule or list of rules to an expression, the solution may be verified:

In[5]:= p /. %5

Out[5]= {0, 0, 0}

What we have done here is to apply each substitution rule (using the back-reference %5) to the original polynomial (kept in the variable p), producing a list of the results of the substitutions; the list confirms that the values found are indeed zeroes of the polynomial. Suppose we just want a list of the three roots? This can be gotten by applying the substitution rules to x:

In[6]:= x /. %5

Out[6]= {1, 2, 3}

Matrices in Mathematica are represented as lists of lists:

In[7]:= {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

Out[7]= {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

To display the matrix in the usual way, the operator MatrixForm is used:

In[8]:= %7 // MatrixForm

Out[8]//MatrixForm=

Image of the matrix

The // operator means "apply the operator to the expression preceding"; in this case, it is equivalent to

MatrixForm[%7].

Mathematica provides all the standard vector and matrix calculations, e.g.,

In[9]:= Eigenvalues[%7]

Out[9]=
Image of {0, (3/2)*(5 - Sqrt[33]), (3/2)*(5 + Sqrt[33])}

A final example, solving a differential equation:

In[10]:= DSolve[f''[x] == a f'[x] + f[x], f[x], x]

Out[10]=
Image of solution to differential equation: {{f[x] -> E^((1/2)*(a - Sqrt[4 + a^2])*x)*C[1] + E^((1/2)*(a + Sqrt[4 + a^2])*x)*C[2]}}

As before, the solution is given as a subsitution rule for f[x]. C[1] and C[2] are the constants of integration. The index notation is used so that all constants defined in a given session will have unique identifiers. Mathematica can solve equations numerically that are not amenable to a closed-form result, and will solve partial differential equations (PDEs) as well as ordinary differential equations (ODEs).


Plotting computational results

A powerful feature of Mathematica is the ability to visualize computational results by plotting them. As an example, suppose we want to see a plot of the solution for the differential equation above. This is easily done:

In[11]:= Plot[Evaluate[f[x] //.
           Join[Flatten[%10], {a -> 1, C[1] -> 1, C[2] -> 0}]], {x, -5, 5}]

Image of plot of differential equation solution

Out[11]=> - Graphics -

Unpacking the input expression, the part starting Join[Flatten . . . takes the solution list for the differential equation and concatenates additional rules to give values for the constants; f[x] is then evaluated and plotted for the range (-5, 5).

A full range of options is provided for Plot, allowing the specification of axes type and labeling, legends, text characteristics, foreground and background colors, etc.

Even more sophisticated effects can be produced by manipulating the Mathematica plot object, as this example (from the online help for Plot) shows:

In[12]:= pp = Plot[Evaluate[{Sin[x], Sin[2x], Sin[3x]}], {x, 0, 2 Pi}];

Image of monochrome plot of three sin functions

This plots three sine functions from 0 to 2 Pi, in the default output color. The ending semicolon supresses the superfluous output line saying - Graphics -. In addition to displaying the plot, it is stored in the variable pp. What is actually stored? One of the most powerful features of Mathematica is that all its results are Mathematica objects, which may be manipulated using Mathematica operators. In this particular case, the plot is a Graphics object, composed of points, lines, and other graphic directives. (If you are familiar with the notion of graphics metafiles, that's essentially what a Graphics object is. You can see the actual metafile by entering FullForm[pp].)

It is beyond the scope of this tutorial to completely explain what's happening in the next input. Suffice it to say that it manipulates the stored plot pp, adding graphics directives to color each plot line in a hue that is proportional to the magnitude of the abcissa, then displays it:

In[13]:= Show[pp /. Line[l:{_, __}] :>
           ({Hue[(0.7*First[Plus @@ #1/2])/Pi], Line[#1]} & )
           /@ Partition[l, 2, 1]];

Image of colored plot of three sin functions

Mathematica also includes a rich set of features for plotting 3-dimensional objects. Here is just a small sampler.

This displays one of the built-in polyhedra:

In[14]:= Show[Polyhedron[GreatStellatedDodecahedron], Boxed -> False];

Image of a great stellated dodecahedron

This shows a random walk within the confines of the unit cube. The first line of input generates a table of random points within the cube, the second constructs a line passing through the points in sequence, and the third adds a graphics directive to color the line, and displays the result:

In[15]:= t = Table[{Random[], Random[], Random[]}, {100}];
           rWalk := Graphics3D[Line[Append[t, First[t]]]];
           Show[rWalk /. Line[ln : ___] -> {Hue[.6], Line[ln]}];

Image of random walk, colored blue, in an outline of a cube

This example plots a function of two real variables, using a small number of plot points, for faster plotting:

In[16]:= Plot3D[Cos[x Sqrt[y]], {x, 0, 4}, {y, 0, 4}, PlotPoints -> 10];

Image of function plot with 10 plot points

After verifying that the plot has the desired form, it can be plotted with more points, and the appropriate decoration, perhaps for publication:

In[17]:= Plot3D[Cos[x Sqrt[y]], {x, 0, 4}, {y, 0, 4},
           PlotPoints -> 100, Mesh -> False,
           FaceGrids -> {{-1, 0, 0}, {0, 1, 0}, {0, 0, -1}}];

Image of function plot with 100 plot points

As with 2D plots, 3D plots have a full range of options, including the addition of styled text to a plot. All Mathematica graphics may be exported as bitmaps (BMP), graphics metafiles (EMF or WMF), or encapsulated PostScript (EPS).

View more graphics examples in the visualization gallery.


Programming in Mathematica

The topic of Mathematica programming would take a large book to explore thoroughly. Here, we just provide a few samples to ilustrate the different programming paradigms that are possible. The main sources of power in Mathematica programming are

  • The fact that the programming language is integrated with a rich, powerful set of mathematics functions.

  • The fact that the programming language can operate dynamically on complex Mathematica objects, using pattern matching and string replacement.

  • The fact that several programming paradigms are available.

The programming language is rather a "Swiss army knife," containing a vast array of features. Given the tight focus on mathematics, this is not overwhelming; and a very small subset can be productively used while the user acquires more expertise. The instant availability of online help and examples makes the learning process fairly painless.

There are some additions one might wish for: object-oriented programming capabilities is one. (See our tutorial on object-orientation for a basic introduction to OO concepts.) The use of industry-standard regular expression syntax, as used by grep and similar tools, is another. These are minor quibbles, though; the language is powerful, and once you are accustomed to it, easy to use.

We will now look at two examples of code used to solve the classic benchmark problem of finding the number of prime numbers between 0 and n, for arbitrary n. The first one is procedural code, based on the sieve of Eratosthenes and very much resembling that algorithm as it would be implemented in C or Pascal:

In[17]:= sieve[n_]:=
    Module[{count, result, i},
      result = Range[n];
      result[[1]] = 0; i = 2;
      While[i^2 <= n,
        If[result[[i]] != 0,
          For[j = 2*i, j <= n, j += i, result[[j]] = 0]];
        i++];
      count = 0;
      For[k = 1, k <= n, k++,
        If[result[[k]] > 0, count++]];
      count]

This defines a function sieve[] taking one argument, the value of n. Module provides a local context for variable names; i.e., even if there are variables elsewhere in the session called count, result, i, or n, they will not conflict with those names within the body of sieve[]. Range[n] returns an array (or list) of the integers 1-n. The remainder of the code, except for minor syntax differences, is essentially the same as the corresponding code in C or Java. (For comparison, here is the Java sieve code.)

The second implementation is functional programming (as is typical of languages such as Lisp or APL). The general idea of functional programming is that you apply functions to functions, building new (larger) functions, until a function is built that takes the given input and produces the given output. "Pure" functional programs have no side effects, meaning there are no loop counters, no modifiable flags, no storage of intermediate results.

Here is our functional program to count primes:

In[18]:= countPrimes[n_] :=
    Length[Select[Range[n], PrimeQ[#]&]]

Understanding functional programs is generally done from the inside out. PrimeQ[#]& builds a function (the equivalent of a Lisp "lambda function") to test its argument for primality. Range[n] returns an array of all the integers 1-n. Select selects from the array the integers that are prime. Finally, Length returns the length of the resultant array of primes.

It is often assumed that functional programming must be slow, because it is high-level. This is not always true, as illustrated by the fact that countPrimes[] counts the number of primes less than 1,000,000 almost six times faster than sieve[]. But . . . there is an optimization we can apply: Procedural code in Mathematica can be compiled for faster execution. The compiled version of sieve[] runs about five times faster than countPrimes[].

Now, it turns out that Mathematica has a built-in function called PrimePi[], which does exactly what we want: Computes the number of primes ≤ n. PrimePi[] is about 20 times faster then the compiled sieve[] in counting the primes less than 1,000,000, and in fact is twice as fast as the Sieve of Eratosthenes written in Java! In case you're interested, here is a summary of all the execution times (for computing the primes less than 1,000,000) on a 650 MHz Pentium under Windows 2000:

Program

Time (milliseconds)

sieve

62,080

countPrimes

11,526

Compiled sieve

2,553

PrimePi

100

Java sieve

252

(If you're interested in how PrimePi works, and the number theory behind primality testing, see the book by David Bressoud and Stan Wagon, A Course in Computational Number Theory. The book uses Mathematica extensively, and includes a CD-ROM with the Mathematica code.)

Next, an example of rule-based or logic programming in Mathematica. This program uses a very simplistic "generative grammar" to produce random English sentences that are semantically meaningless, but syntactically correct, e.g., "The tall girl denigrates a notorious horse." The grammar is defined in terms of rules; the program, using pattern matching, substitutes for occurrences of variables in the rules, until no further substitutions are possible. This is similar to the way the problem would be attacked in the logic programming language Prolog. Selecting the substitutions has a random element, thus many different sentences can be generated.

The pick[] function takes a list of items as argument, and randomly selects one item in the list:

In[19]:= pick := #[[Random[Integer, {1, Length[#]}]]]&;

The variable generativeGrammarRules is defined as a list of rules: A sentence is a noun phrase (np) followed by a verb phrase (vp); np and vp are defined by further rules; and so on, until the lowest-level rules define concrete articles, nouns, verbs, and prepositions. Note the use of :> instead of -> in defining the rules. This indicates that Mathematica should not attempt to evaluate the rule until it is used. (If the rules were evaluated immediately, the random selection would occur only once, and every generated sentence would be the same.)

In[19]:= generativeGrammarRules := {
    sentence :> {np, vp},
    np :> {article, adjective, noun},
    vp :> pick[{{verbIntransitive, pp}, {verbTransitive, np}}],
    pp :> {preposition, np},
    article :> pick[{a, the}],
    adjective :>
      pick[{red, tall, strange, warm, furious, bizarre, nice,
            wonderous, notorious}],
    noun :>
      pick[{boy, girl, cabbage, king, automobile, horse, building, bird,
            thing, forest}],
    verbIntransitive :>
      pick[{goes, went, flew, travelled, exits, wandered, stumbled}],
    verbTransitive :>
      pick[{hits, kissed, insulted, rules, watches, denigrates,
            impersonated, becomes}],
    preposition :> pick[{to, toward, from, into}]
    }

Next, we generate a sample sentence by applying generativeGrammarRules to the top-level goal, sentence. Recall that the operator //. means "keep applying the rules until no further substitution is possible."

In[20]:= sentence //. generativeGrammarRules

Out[20]:= {{a, wonderous, girl}, {exits, {toward, {the, wonderous, automobile}}}}

This looks OK, except for the superfluous list constructs. The following function gets us further towards the goal:

In[21]:= getSentence := ToString[Flatten[sentence //. generativeGrammarRules]]

In[22]:= getSentence

Out[22]:= {a, notorious, king, hits, the, warm, bird}

Finally, this function takes the output of getSentence and makes all the appropriate transformations to produce a lexically correct sentence:

In[23]:= printSentence[s_] :=
      Module[{sentence},
      sentence = StringReplace[s, {"{" -> "", "," -> "", "}" -> ""}] ;
      StringReplacePart[sentence,
        ToUpperCase[StringTake[sentence, 1]], {1, 1}] <> "."]

Now, using these functions, we produce 20 random sentences:

In[24]:= TableForm[Table[printSentence[getSentence], {20}]]

Out[22]//TableForm=
    A red cabbage insulted the bizarre horse.
    The furious building kissed the nice bird.
    The furious cabbage rules a bizarre bird.
    A furious building went toward a furious king
    A bizarre cabbage watches a nice thing.
    The strange horse watches the wonderous automobile.
    The tall girl denigrates a notorious horse.
    The furious boy flew into the warm automobile.
    A wonderous girl kissed a wonderous horse.
    The tall automobile stumbled into the furious thing.
    A nice boy insulted the red boy.
    The red automobile denigrates a furious girl.
    The red girl wandered from the wonderous automobile.
    A bizarre boy denigrates a tall automobile.
    A strange automobile went into the nice boy.
    The wonderous horse travelled into the bizarre boy.
    The furious girl denigrates the notorious king.
    A nice king goes toward a furious horse.
    The bizarre king went toward a nice girl.
    A warm bird exits toward the furious building.

This brief tutorial only scratches the surface of what is possible with Mathematica programming; we hope it is sufficient motivation to learn more.


Using Mathematica for technical publishing

Mathematica notebooks may be published without further formatting. MathSource, established in 1990, is a large electronic library of Mathematica materials, including notebooks. Notebooks may be submitted directly to the ArXiv preprint archive maintained by Cornell University and the Los Alamos National Laboratory. (See ArXiv's "Considerations for Mathematica Notebook Submissions" or the Wolfram Research "Guidelines for Submitting Notebooks" for more information.)

The internal format of a Mathematica notebook is entirely text-based, and system-independent. It is thus highly portable, as long as the recipient has a means of viewing it. For those who do not have Mathematica, Wolfram provides MathReader, a free reader for notebooks. MathReader provides a read-only view of the notebook that is compatible with full-function Mathematica.

Mathematica notebooks may be converted into a variety of standard formats for printing or display, such as PostScript, TeX, MathML, and HTML. A striking example of the versatility of Mathematica in producing typeset output is the fact that entire books have been produced in camera-ready form as Mathematica output; for example, the book mentioned above, A Course in Computational Number Theory, by David Bressoud and Stan Wagon. (This book also illustrates the power of Mathematica in a field - number theory - not traditionally taught with computational software.)

For an example of a Mathematica notebook, and the same notebook automatically converted into HTML, see our reliability analysis page.

In addition to publishing Mathematica results on the Worldwide Web as static content (HTML and MathML), dynamic and interactive mathematical content can be placed on the web using webMathematica. This technology enables the creation of web sites that allow users to compute results and display typeset and graphical output directly from a web browser. For more information and demonstrations, see our webMathematica page.


Integrating Mathematica with other languages: MathLink and J/Link

For tasks requiring interfaces to the external environment Mathematica provides MathLink, which allows Mathematica programs to communicate with external programs or vice versa. MathLink can be used with programs written in C, Java, or other languages.

J/Link is an extension of MathLink providing additional power and ease-of-use to programmers using the Java language. Using J/Link and JSP (Java Server Pages), webMathematica provides the capability of creating pages with dynamic, interactive mathematical content on the Worldwide Web.

See our MathLink page for a more detailed view of MathLink, J/Link, and webMathematica; we also have a webMathematica examples page.


Links

has complete information on the Mathematica product, pricing, related products and features, etc. The Wolfram Research site also has samples from various applications of Mathematica, documentation, technical information, and an online edition of The Mathematica Journal. They also have the full text of The Mathematica Book by Stephen Wolfram online.

MathGroup is a moderated email list and internet newsgroup, formed in the 1980s. It is a very active list, a good way to get questions answered, and a source of sample code. The current thread for the list is maintained by Google.com (or use your favorite newsreader and subscribe to comp.soft-sys.math.mathematica.*). Wolfram Research maintains a searchable archive of MathGroup postings.

MathSource, mentioned above, is a large searchable archive of Mathematica materials.

There is information on Mathematica education at the Wolfram Research web site. Stan Wagon and Ed Packel teach some excellent summer courses in the Colorado Rockies, at Rocky Mountain Mathematica. The University of Massachusetts CyberEd has some Mathematica courses taught on the Web by Ken Levasseur.

Visit some of our other web pages: There are interesting Mathematica graphics examples in the visualization gallery. The reliability analysis page has a notebook and package file with examples of Mathematica applied to this application area. The webMathematica page has interactive examples of Mathematica functionality delivered on the web. The financial engineering page has links to uses of Mathematica in finance and economica.


About Mathematica Download MathReader MathSource