Mathematical Modeling and Mathematica

Lab 1:  Introduction to Mathematica

John E. Cruthirds and L. Richard Hitt
Department of Mathematics and Statistics
University of South Alabama

Objective

This lab has two objectives.  First, this lab will help you gain the necessary skills for using the Macintosh computer and the notebook user interface for the program Mathematica .  Second, the lab will demonstrate some of the capabilities of Mathematica  by way of several examples.

Getting Starting

Mathematica  is a powerful desktop computer program capable of doing algebraic calculations, numerical approximations, and computer graphics.

The program consists of two main parts, the kernel and the front end.  The front end contains the user interface you are  working in now.  The kernel is the part of the program responsible for all of the mathematical calculations.  Only the front end is required to open a notebook.  The kernel may or may not be running. If it is not, it will start whenever a calculation needs to be made.  Once it is running, it remains running until you stop it.
There is a help system available for both the front end and the kernel.  Just use the usual pull-down Help menu.
For the kernel, you can obtain information about any built-in command by typing a single question mark followed by the command name, e.g., ?Plot.  Typing two question marks followed by the command name gives you additional information.

To begin with, let's have Mathematica  perform some simple computations.  First, let's see if we can calculate 1+1 .  To do this, you can move the cursor to any place in the notebook where the cursor symbol is a horizontal I-beam, then type in the expression followed by the <shift><enter> combination.   Or, if the expression is already in a notebook, as below,  you can click the cursor in the cell containing the expression and press the <shift><enter> combination.  This action will send the expression to the kernel to be evaluated.  If the kernel of Mathematica  is not already running, it will need to start.  This can take several seconds.  But after the kernel is started, future simple caluclations will proceed much more quickly.  So, place the cursor in the next cell, click once and press <shift><enter>.  If you prefer, you can just use the <enter> key on the numeric keypad rather than the <shift><enter> combination to send commands to the kernel.

1 + 1

After a possible wait for the kernel to start, you should see the much awaited result.  Note that Mathematica  keeps track of the statements entered into the kernel and sent out from the kernel.

Now that we know about addition, let's look at the other arithmetic operations.  They are all illustrated in the following expression.  In that expression, x y denotes "x times y".  You can also use x*y for multiplication.  The carat symbol (^) denotes exponentiation.

(3  +  7)*8/((4 - 8)^12)

Now click the cursor in the blank space below and enter any arithmetic expression you want followed by <shift><enter>.

Okay, so we see that Mathematica  can be used as a calculator.  In the next section we will examine some of the more mathematical capabilities of Mathematica .

A Brief Tour of Mathematica

In this section we will give some examples of the capabilities of Mathematica .  Additional examples and fuller explanations can be found in Stephen Wolfram's book Mathematica .  You should execute each input cell by clicking the cell and pressing the <enter> key.  You should freely experiment in this notebook with the capabilities of Mathematica  by creating your own input cells.

Graphing

Mathematica  has several built-in graphics functions which allow curves and surfaces to be graphed with relative ease.

First, we will do a 3-dimensional example like you encountered in your calculus course on functions of several variables.

Plot3D[((x y)/((x^2) + (y^2) + .1)), {x, -1, 1}, {y, -1, 2}]

Many of Mathematica 's commands have options which can be specified.  Here is a slight variation on the previous example using one of the options for Plot3D.  Rather than having Mathematica  re-computing all of the points on the graph, we can use the Show[%, options] to change the display options of the previous graphic.  Mathematica  uses the % symbol to refer to the most recent computation.

Show[%, AxesLabel -> {x, y, z}]

Here is the same graph with a label.

Show[%, PlotLabel -> Mathematica Surface]

For a complete list of the options available for Plot3D (or for any other Mathematica  function for that matter) you can refer to the book Mathematica  by Stephen Wolfram.

Study the previous images to see how the axes are oriented by default in Plot3D.  Can you see where the first octant (the region of 3-space in which each of the variables x, y, and z is positive) is located?

Another function of 2-variables we can try is given below.  Note that this example, as well as the previous one, are slightly beyond the usual graphing done by hand in a calculus course.

Plot3D[
      ((((x^2) - (y^2)))^2) - (((x y))^2), {x, -1, 1}, {y, -1, 1}]

We can modify the appearance of the above plot using some options.

Plot3D[
      ((((x^2) - (y^2)))^2) - (((x y))^2), {x, -1, 1}, {y, -1, 1}, 
      PlotPoints -> 21, BoxRatios -> {1, 1, .8}, 
      ViewPoint -> {.9, -2.4, .75}]

A Note on Memory (RAM):  Graphing, especially in 3-dimensions, uses up memory quickly.  The scroll bar in the lower left of the window indicates how much memory has been used.  When all the memory is used, Mathematica  will perform unpredictably, often causing the machine to hang.  At that point, you cannot save the notebook you have been working on.  You must restart the machine.  

Moral:
  1.  save your work often during your session (if you want to keep it); and 
  2.  watch the memory scroll bar.

For plotting 2-dimensional graphs of a function of 1 variable, the Plot command is used.

Plot[(x^4) - 4 (x^3) + 1, {x, -1, 4}]

Can you see the two critical points and the two inflection points in the above graph?  To aid in estimating the coordinates of points, we can add options to the above plot.

Show[%, GridLines -> Automatic, 
      AxesLabel -> {"x", "y"}]

For another example, let's plot a curve with a skew asymptote.

Plot[(((x^3) - 1)/((x^2) - 1)), {x, -.9, 5}]

Let's plot the asymptote in blue, and then superimpose the function and its asymptote.

Plot[x, {x, -1, 5}, PlotStyle -> RGBColor[0, 0, 1]]Show[%, %%]

Mathematica  can also plot parametric curves in the plane.  The following example is a well-known curve.  Do you recognize it?  Can you see the effect of the AspectRatio option?

\(ParametricPlot[
	{t - Sin[t], 1 - Cos[t]}, 
	{t, 0, 3\ π}, 
	
      AspectRatio -> 2\/\(3\ π\)]\)

We return to surface graphs for a final example.  Many surfaces cannot be described as a graph of a function f(x,y).  A hyperboloid of 1 sheet is an example of such a surface.  In order to graph these surfaces, you need to be describe them using sets of parametric equations.  Once you have a surface described as a set of parametric equations in two parameters, you can use the Mathematica  function ParametricPlot3D to graph the surface.  Cylindrical coordinates can be used to produce an easy parameterization of the hyperboloid described in rectangular coordinates by the equation

(x^2)  +  (y^2)  -  (z^2)  =  1

Clear[r, theta, z]\(r[z_] := \((1 + z\^2)\)\^.5\)ParametricPlot3D[{r[z] Cos[theta], r[z] Sin[theta], z}, {z, -2, 
        2}, {theta, 0, 2 π}]

Symbolic Computations

Mathematica  has symbolic computing capabilities including algebra and calculus.  Additionally, Mathematica  can learn any computational rules you want to teach it.

Expanding and factoring polynomials can be done with

Expand[(((1 + x - (x^2)))^21)]

and

Factor[(x^100) + 1]

Differentiation and integration are also built-in operations:

(∂_x) Log[(x^3) + Sin[x]]

(∂_x)(( (x^3) + x - 1)/((x^2) - 1))

Simplify[%]

∫x (Sqrt[(x^2) + 1]) \[DifferentialD]x

Of course, you can't expect Mathematica  to handle all indefinite integrals.  Can you think of an integral that Mathematica  can't evaluate?  Try out your ideas.

If you need to compute a definite integral, the syntax is like this

(∫_0^(((3 π)/4)))Sin[x]^4 Cos[x]^6 
        \[DifferentialD]x

That last calculation took Mathematica  some time, but note that Mathematica  gave the exact answer.  If all you need is an approximation to a definite integral, you can use the command NIntegrate to give a direct numerical approximation of a definete integral without going through the exact calculation.  Numerical methods are discussed in the next subsection.

Mathematica  also knows about power series.  The next example computes the 20th degree Taylor polynomial about x=0 (sometimes called a Maclaurin polynomial) for the given function.

Series[((x^2) - 1) Sin[(x^2)], {x, 0, 20}]

Limit calculations are also possible symbolically.  For example, Mathematica  can calculate the following limit to be e, rather than just some approximation to e .

Limit[(((1 + (1/x)))^x), x -> ∞]

Solving algebraic equations symbolically (as opposed to numerically) is also part of the built-in capabilities of Mathematica , as the following examples illustrate.  Note that the answers are exact.

Solve[28 (x^2) - 51 x - 27 == 0, x]

Solve[(x^2) - 2 x + 3 == 0, x]

Solve[{3 (x^2) - 5 y == 1, 2 x + 3 y == -1}, {x, y}]

As the middle example above (the one marked see below) shows, you don't necessarily get a simplified answer.  To remedy this,  you can specifcally request it, however.

Simplify[%%]

Mathematica  can compute exact solutions to differential equations as is illustrated in the following example.

DSolve[y''[x]-5 y[x]==1,y[x],x]

Numerical Calculations

Mathematica  is capable of numerical precision to any prescribed accuracy.

For example, to compute the value of p to 500 decimal places, you can enter

N[π, 500]

Mathematica  can also act as a scientific calculator, with the additional benefit that you can specify as much accuracy as you wish.

(2^500)

N[%]

N[%%, 100]

You can also find approximations to roots of equations with Mathematica  using the FindRoot command.  In simple cases, FindRoot uses Newton's method, so you must also specify a starting point.  FindRoot then reports the first root it encounters (there may be others).  In some cases you need to use FindRoot in conjunction with Plot to determine a good starting point.

FindRoot[(x^11) - 3 (x^7) + x - 1, {x, 2}]

And you can factor integers as in

FactorInteger[28839650461243243243243243214403592782]

In the previous subsection, we computed the exact value of the definite integral of 
Sin[x]^4 Cos[x]^6 on the interval {x, 0, 3Pi/4}.  Computing the required anti-derivative is somewhat involved.  If you are only interested in a numerical answer, it is often faster to use a numerical routine to approximate the value of the definite integral avoiding the symbolic difficulties.  This feature is illustrated next.

NIntegrate[Sin[x]^4 Cos[x]^6, {x, 0, ((3 π)/4)}]

NSolve (the numerical analogue to Solve from the previous section) can be used to produce numeric, rather than exact, solutions to algebraic equations.  Mathematica  can also solve systems of equations numerically.  Differential equations, and systems of differential equations, can be solved using the NDSolve (analogous to the DSolve in the previous section) for exact and numerical solutions, respectively.  These topics are explored more thoroughly  later in the course.

Lists and Tables

Lists are an important construct in Mathematica  which will be used repeatedly in future labs.  The following command makes a list of the squares of the first twenty positive integers.

Table[(i^2), {i, 1, 20}]

Next, we plot the values in the list

ListPlot[%]

A matrix is a list of lists.  The next command sets a string equal to a matrix whose (i,j)-entry equals the greatest common divisor of i and j.

Clear[mat1]mat1 = Table[GCD[i, j], {i, 1, 6}, {j, 1, 6}]

If you want the list to look more like a matrix you can use the command

MatrixForm[mat1]

We can compute the determinant of the matrix with

Det[mat1]

Since the determinant is non-zero, we can calculate the inverse matrix.

Clear[mat2]mat2 = Inverse[mat1]

Finally, we can verify that the product of the matrix and its inverse is the identity matrix.

MatrixForm[mat1.mat2]

Using Packages

Mathematica  comes with several packages for special applications.  Packages must be loaded into a session before they can be used.

The various packages are located in the Packages sub-folder of the Mathematica folder.  Information about them can be found in the book Mathematica Packages  which is part of the standard Mathematica  distribution.

The following example illustrates the use of a package.

<< "Graphics`Polyhedra`"

This command loads the package Polyhedra located in the Graphics subfolder of the Mathematica folder.  

Now that the package has been loaded, we can use some of the commands which are defined in the package.

Show[Polyhedron[GreatIcosahedron]]

Programming in Mathematica

Mathematica  is also a high-level programmig language with capabilities for iteration, looping, user-defined functions, etc.

The following code displays the graphs of a function for several different values of the parameter a.  For the purpose of displaying the results on the hardcopy version, the resulting graphics have been placed into an array using the GraphicsArray command.  (See the Implementation section at the end of the lab for the code used to do this.)

Clear[f, x, a]f[x_, a_] := (x^3) + a x + 1; Do[Plot[f[x, a], {x, -3, 2}, PlotRange -> {-2, 3}], {a, 
        -3, 2}]

The above example involved a straightforward Do loop which generates a list of graphics.  One very useful feature about such a list is that it can be animated.  If you select the graphics by clicking the appropriate cell bracket, choose the Graphics menu, then choose Animate Selected Graphics, an animation will begin.  You can control various aspects of the animation by clicking the buttons in the lower left of the window.  Click anywhere in the middle of the window to stop the animation.

In addition to the usual programming constructs, Mathematica  also makes extensive use of Lists and Tables.  To illustrate this, we will compare the graphs of Sin[x] with those of its first eight Maclaurin polynomials.  Rather than inputting the formulas for the polynomials by hand, and rather than use the Mathematica  built-in command Series, we will build a table of the polynomials all at once.  This is done in a single line of input to Mathematica  (spread out over the first seven lines of code below for readability).  Note that this line of input contains what would amount to a nested double Do loop in many other programming languages.

Clear[functionlist]functionlist = 
      Table[(∑_(i = 0)^n)
            (((((-1))^i) (x^(2 i + 1)))/((2 i + 1)!)), {n, 0, 
          7}]; AppendTo[functionlist, Sin[x]]; colorlist = Table[RGBColor[0, 0, t], {t, .1, 1, .(9/7)}]; AppendTo[colorlist, RGBColor[1, 0, 0]]; Plot[Evaluate[functionlist], {x, 0, 7}, PlotStyle -> colorlist]

Exercises

A notebook containing solutions to the following exercises should be "turned in" as your lab report (as described in the first day handout).  Each student is responsible for writing a lab report independently.

Exercise 1

Find a 10-digit number which is prime.

Exercise 2

Plot a graph of the function f(x,y) =  Cos (Sqrt[(x^2) + (y^2)]) over some suitable region in the xy-plane containing the origin.  Experiment with the region and possibly with the PlotPoints option of Plot3D to obtain a pleasing and informative rendering of the graph.

Exercise 3

Modify the Maclaurin polynomial graphing code found in the Programming in Mathematica  section of Lab 1 to compare the graphs of Cos[x] with those of its first six (not eight) Maclaurin polynomials.

Exercise 4

Let  f(x) = 2  (x^3) - 6x + 3  and  g(x) = -4 (x^3) + 3  (x^2) + 2 .  
(a)  Use the graphing capabilities of Mathematica  to graph both functions on a single set of axes.  Examine the graphs and visually estimate the number of points of intersection of the two curves as well as the coordinates of the points of intersection.
(b)  Use the symbolic capabilities of Mathematica  to find the exact values of the x and y coordinates of the points of intersection of the two curves.
(c)  Use the numerical capabilities of Mathematica  to find approximate values for the x and y  coordinates of intersection of the two curves.

Exercise 5

Consider the function f(x) = (((x^3)  +  x  +  1)/((x^4) +  1))
(a)  Using the symbolic capabilities of Mathematica , find simplified formulas for f'(x) and for f''(x).
(b)Find all real roots of f'(x) and of f''(x).  These numbers are then candidates for relative extrema and for inflection points.
(c)  Rather than applying the first or second derivative tests to classify the critical points, simply graph f(x), f'(x), and f''(x) on the same set of axes over some appropriate interval and interpret what you see.  Give a full explanation of which points found in (b) above are relative extrema and which are inflection points.  To keep the three graphs straight, plot them in blue, red, and green, respectively.

Implementation

The following code was used to generate the array of graphics found in the Programming in Mathematica  section.

Clear[f, g, glist, x, a]f[x_, a_] := (x^3) + a x + 1; g[a_] := 
      Plot[f[x, a], {x, -3, 2}, PlotRange -> {-2, 3}, 
        DisplayFunction -> Identity]; glist = Table[g[a], {a, -3, 2}]; Show[GraphicsArray[Partition[glist, 3]]]