Getting Started with Mathematica

©1999 by Gerald Teschl  <gerald@mat.univie.ac.at>, <http://www.mat.univie.ac.at/~gerald/>
©2000 adapted by Roland Steinbauer <roland.steinbauer@univie.ac.at>, <http://www.mat.univie.ac.at/~stein/>

Basic calculations and variables

Mathematica is a powerful tool for doing mathematics. It can handle both symbolic and numeric expressions. You can use it just like a calculator: you type in questions, and Mathematica prints back answers.

27 + 5^3

A space between two expressions is interpreted as multiplicatio.

4 12

2/3

Mathematica tries to be as precise as possible. To get numerical results use:

N[%]

As you might have guessed % is substituted by the last output. To get back the last but one output use %%. 
To reach even higher precision you can tell Mathematica how many digits you like.

N[%%, 20]

You can also use variables or put several commands into one cell.

x = 5
27  + (x^3)

If you wonder how I could input the power as a superscript, go to the File menu and select Palettes->BasicInput. If you put a semicolon at the end of an input sequence the respective output is suppressed. So in real life you might want to use the following.

x = 5;
27  + x^3

You might have noticed that Mathematica assigns  numbers to every command you input and to the corresponding  output. This makes it more comfortable to use the output of the previuos calculations. Moreover all results are stored and you can use them in any following calculations as long as you do not quit Mathematica (more precisely the kernel).

Out[8] 3

Can you explain this result? Note that Out[8] was suppressed and remember that a space between two expressions is interpreted as multiplication. Be warned that if you omit this space, you will get unexpected results!

xy  +  x y

Mathematica also knows a lot of basic constants and operations.

Pi

To get numerical values use:

π // N
E // N

Functions

Mathematica has a large amount of functions already built in. The arguments of a function are put in between square brackets and separated by commas. Some basic functions are given in the table below:

For example, we can compute

Sin[1]

Well, this might not be the answer you have expected! Mathematica just returns your input unevaluated. The reason is that we have specified an exact argument (one), and-as already indicated above- Mathematica tries to find an exact solution in this case. Since there is no closed form to our input, Mathematica leaves it as it is. To can tell Mathematica that the input is not an exact number by adding a dot:

Sin[1. ]

Alternativcel you already know how to tell Mathematica that you want to get numerical output.

N[%%]

You can even define your own functions as follows:

f[x_] := (x^2)

In this expression the underscore as well as the colon are essential; we shall explain their meaning below. For the time being just remember not to forget it! 
Now you can use your function:

the underscore represents a pattern. A single underscore will match a single expression (argument) and x is the name of the pattern (it can be used to refer to the matched expression on the right hand side). The colon tells Mathematica not to evaluate the right hand side. This is why you get no output.

f[3]

f[a]

g[x_] := Sqrt[x] + 1

g[3]

g[3. ]

g[a] + 3

We may apply transformation rules  to functions.

h[7]

h[7] /. a -> 3

h[x] /. x -> 7  /. a -> 3

In order not to loose control we may look at what we have defined so far.

?f

?g;?h

To undo the assignments we use:

Clear[f, g, h]

Now we come back to the role of the underscore in defining functions: The most powerful aspect of transformation rules in Mathematica is that they may not only involve litteral expressions (as above) but also patterns.  Any expression ended by an underscore is such a pattern. The definition of f[x_] specifies how the function with any argument should look like. And that is what we really want to do if we define the function f. With other words f[x_}:=x^2 tells Mathematica to apply the transformation f[anything_]->anything^ 2 whenever possible. 
To make this point even more clearly let's have a look at what happens if we omit the underscore.

f[x_] := x^2
g[x] := x^2

f[2]
g[2]

f[y]
g[y]

g[x]

Can you explain this? Remember we have set x to 5 long time ago...To avoid this problems clear any variables and functions no longer needed.

Clear [x];  x

x := 5; y := 27; y

y =. ; y
Clear[g]

Finally let's see what happens if we omit the colon in defining functions

g[x_] = (x^2) + Sin[x]

The output shows that Mathematica has evaluated the expression before making the assignment. In particular, we get

g[a] + 3

Can you explain this result? Look at the definition of g:

?g

Do you know now what is going on? To avoid any such problems you should usually stick to the underscore and colon version and undo assignments which are no longer needed!

Clear[x, g]

Plotting Functions

One of the most important features of Mathematica is its capability of visualizing different types of data. The basic commands for plotting functions of one argument are

For example let us plot the function x^2.

Plot[x^2, {x, -2, 2}]

Plot[{Cos[ϕ], Sin[ϕ]}, {ϕ, -2 π, 
        2 π}]

Mathematica will automatically try to find appropriate scales. However, if the function has singularities it is often better to specify the plot range as an option.

Plot[Log[x], {x, 0, 1}]

Plot[Log [x], {x, 0, 1}, PlotRange -> {-6, 0}]

All options are implemented as rules and are hence of the form OptionName -> OptionValue. There are numerous other options available to control the appearance of a plot. See the online documentation for more information.

The command

Display["myfunction.eps", %, "EPS"]

will save the previous graphics as an eps file which can then be included in other applications. Other formats are available as well.

Differentiation and Integration

Mathematica can be used to calculate derivatives of functions. The basic syntax is

({{"\!\(\*StyleBox[\"\\\"D[\\\"\", \"MR\"]\)\!\(\*StyleBox[\"\\\"f\\\"\", \"TI\"]\)\!\(\*StyleBox[\"\\\",\\\"\", \"MR\"]\) \!\(\*StyleBox[\"\\\"x\\\"\", \"TI\"]\)\!\(\*StyleBox[\"\\\"]\\\"\", \"MR\"]\) ", "derivative "of f with respect to x" "}, {"\!\(\*StyleBox[\"\\\"D[\\\"\", \"MR\"]\)\!\(\*StyleBox[\"\\\"f\\\"\", \"TI\"]\)\!\(\*StyleBox[\"\\\",\\\"\", \"MR\"]\) "{"\!\(\*StyleBox[\"\\\"x\\\"\", \"TI\"]\)\!\(\*StyleBox[\"\\\",\\\"\", \"MR\"]\) \!\(\*StyleBox[\"\\\"n\\\"\", \"TI\"]\)"}"\!\(\*StyleBox[\"\\\"]\\\"\", \"MR\"]\) ", "repeated derivative " " "}})

Lets look at some examples.

D[x^2, x]

D[Log[(1 + x^2)/(1 + x)], 
      x]

Hm...That does not look too nice,does it. So lets try the following

Simplify[%]

Mathematica can also be used to compute arbitrary integrals.

For example

∫(1/((x^4) - 1)) \[DifferentialD]x

Let's differentiate the expression in order to get our integrand back.

D[%, x]

Ups! At first sight it looks like Mathematica made a mistake somewhere along the way. However, again performing some simplifications it is not hard to see that this expression is indeed equivalent to our original integrand.

Simplify[%]

Let's see if we also get back the function involving the logarithm above

Integrate[%4, x]

Asimple examle of a definite integral.

Integrate[Cos[x]^2, {x, 0, 2 Pi}]

Complex  Numbers

Mathematica of course also knows how to handle complex numbers

Sqrt[-4]

You enter a complex number just by using a capital I:

((4 + 3 I)/(2 - I))

The most important operations with complex numbers are collected in the following table.

However, note that Mathematica will not automatically evaluate real or imaginary parts for you

Re[Sin[x] Exp[x + I y]]

You can get the answer using the built in function ComplexExpand:

ComplexExpand[%]

Note that all variables are assumed to be real! If you don't want this you can use

ComplexExpand[Exp[x], x]

You can also use a list of variables as second argument if there are more than one complex variables in the expression. Lists are enclosed in curly brackets.

ComplexExpand[y Exp[x], {x, y}]

Solving Equations

Mathematica can solve various kinds of equations. For example set

eqn =  (x^2) +  2 a x  +  b == 0

Note that the Set operator (=) has lower precedence than the Equal operator (==). To solve this equation for x you use the command

sol = Solve[eqn, x]

Note that the result is given as a list of rules. To verify this solution we can substitute the solution back into the equation and simplify the result.

Simplify[eqn  /.  sol]

In summary we have

If you are only interested in, say, the first solution, you can use the Part operator to extract it.

Part[sol, 1]

or equivalently.

sol[[1]]

You can also solve systems of equations for several variables using lists.

For example

eqns = {x + y == a, 
          x - y == 0};
Solve[eqns, {x, y}]

If you are looking only for a numerical solution  you can also use

FindRoot[Sin[x] == Cos[x], {x, 1}]

Here, the number after the variable is a start value for the algorithm.

Clear[eqn, eqns, sol]

Simplifying expressions

You have already seen the Simplify command which does a sufficient job on most expressions. However, often further simplifications can be made if certain additional properties are known. Such additional assumptions can be given as a second argument to Simplify.

Simplify[Sqrt[(x^2)], x ∈ Reals]

Using this approach, Mathematica can even verify inequalities:

Simplify[(((a b c))^(1/3)) ≤ (1/3) (a + b + c), 
      0 ≤ a && 0 ≤ b && 0 ≤ c]

Here && corresponds to a logical And. Similarly, || would correspond to a logical Or.

If Simplify should not suffice, you can also try to use FullSimplify which applies a wider range of transformations (but consequently takes more time). In particular, FullSimplify will do much better on expressions involving special functions.

Simplify[Gamma[1 - x] Gamma[x]]

FullSimplify[Gamma[1 - x] Gamma[x]]

These two commands are useful for polynomials

Expand[(((1 + x))^3)]

Factor[%]

Limits

Of course Mathematica is also capable of computing limits of sequences and series. The basic syntax of the Limit command is given in the following table.

By the way you can get short help message on a certain Mathematica function by querying using a question mark.

? Limit

Now we go on to claculate the limist of real sequences.

Limit[1/n,  n -> ∞]

Limit[n^ 2,  n -> Infinity]

Limit[(n^2+1)/(2n^2+7n-5), n->∞]

Note that Mathematica does not distinguish between n->Infinity (n natural) and x->Infinity (x real).

Limit[(x^2+1)/(2x^2+7x-5), x->Infinity]

Limit[(n^2+1)/(2n^2+7n-5), n->Infinity]

Lets hav a look at sone further examples

Limit[(1+a/n)^n, n->Infinity]

Limit[((Sin[x + h] - Sin[x])/h), h -> 0]

Limit[(a x+3)/(b x+7), x->-Infinity]

What happens if we try to compute the limit of non-converging sequences?

Limit[(-1)^n, n->Infinity]

Limit[5 Sin[1/x],x->0]

What about left and right sided  limits?

Limit[1/x, x -> 0]

So Mathamatica by default computes the right sided limit. To get the left sided limit use this.

Limit[1/x, x -> 0, Direction -> 1]

Whereas to explicitly get the right handed limit you may enter.

Limit[1/x, x -> 0, Direction -> -1]

However the following examples are due to warn you about the capabilities of Mathematica's Limit function.

Limit[(a x^2 +x)/(a x^2 +1), x->Infinity]

Limit[Log[x],x->0,Direction->-1]   
                  (* Grenzwert x-> -0 *)

That's nonsense, right?

f[x_] := x - IntegerPart[x];
Limit[f[x], x -> 3, Direction -> 1]

That's simply not true!!! See here...

Plot[x - IntegerPart[x], {x, 0, 4}]

Further you will get into trouble here. Remember E represents the Euler number.

Limit[E^x, x->Infinity]

Limit[a^x, x->Infinity]

Limit[a^x, x->Infinity]/.a->-1/2

Limit[a^x, x->Infinity]/.a->-2

To compute certail-innocently looking-sequences you'll need to load additional packages into Mathematica. Such packages contain additional functions not implemented in the Mathematica kernel.

Limit[n!/n^n,n->Infinity]

Needs["Calculus`Limit`"]

Limit[n!/n^n,n->Infinity]

To see what packages are loaded at the moment use this.

$Packages

Series

The basic syntax for summation is the following.

Or as you already know...

?Sum

Let's  first compute some finite sums.

Sum[1/n^2,{n,1,10}]

Here we take only even n's.

Sum[1/n^2,{n,2,10,2}]

We test if the second result is really smaller than the first one.

% < %%

Next we turn to the issue of infinite series. As you might have guessed we just have to insert Infinity as imax.

Sum[1/n^2, {n, 1, Infinity}]

We can also calculate numerical limits.

NSum[1/n^2, {n, 1, Infinity}]

Is that correct?

N[Pi^2/6, 30]

If you need higher accuracy...

NSum[1/n^2, {n, 1, Infinity}, AccuracyGoal -> 30, 
      WorkingPrecision -> 40]

?AccuracyGoal

?WorkingPrecision

What about divergens series.

Sum[1/n, {n, 1, Infinity}]

However, see  this.

NSum[1/n, {n, 1, Infinity}]

That's one of the most 'famous' examples of failure Computer systems as Mathematica. Note that the number produced above does not have any meaning...

Sum[1. /n, {n, 1, 10^57}]

Timing[s = Sum[1. /n, {n, 1, 10^1000000}]]

?Timing

Here's another warning example.

Sum[(-1)^n n/(n+1),{n,1,Infinity}]

NSum[(-1)^n n/(n+1),{n,1,Infinity}]