Wyższa Szkoła Zarządzania i Bankowości
LECTURESNOTEBOOKSPACKAGES

8 Appendix: Introduction to Mathematica


1 Introduction to Simulation and Modeling
2 Discrete Medeling (L-Systems)
3 Population Dynamics
4 Number Representation and Error Propagation
5 Modeling with Random Numbers
6 Heat Transfer in a Rod (Connection Mathematica and C: MathLink)
7 Special Topics in Stochastic Finance
8 Appendix: Introduction to Mathematica
9 Population Dynamics in Vensim®PLE
     
 

Acknowledgements

Parts of the material in this section was taken from a number of sources, which are listed below

Mathematica 4.0, S. Wolfram.
Mathematica User's Guide to the X Front End, Wolfram Research.
Mathematical Modelling and Mathematica, J.E. Cruthirds and L.R. Hitt, Department of Mathematics and Statistics, University of South Alabama, material taken from the Web.
An introduction to Mathematica, N. Blachman, material taken from the Web.

Introduction and demands for Report

This notebook will give an introduction to Mathematica. It gets you acquainted with a number of Mathematica. functions, and introduces the user interface.

At the end of the notebook you will find a number of exercises.

A  Introducing Mathematica

A.1 The Mathematica Front End and Kernel

A.1.1 The Mathematica environment

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

Mathematica consists of two parts, the Kernel, which is the computational engine, and the  Front End, which acts as the user interface to the Kernel. The Mathematica Kernel is essentially identical on all computer systems. The Front End may differ from one (operating) system to another. Mathematica  can be operated in many ways. The Kernel and Front End can both run at the same computer, or the Kernel may run on a powerful server with the Front End running on your local host. If a computation must be carried out, the Front End contacts the Kernel, e.g. through the network. Although the details of running Mathematica differ from one place to another, the structure of Mathematica calculations is the same in all cases. You enter input, then the Mathematica Kernel processes it, and returns the result.

You will be using the Notebook Front End, which is available on many systems (Macintosh, Windows, Unix, etc.). Section 1.2 will discuss the Notebook Front End in more detail.

During the lab session you will be using Mathematica 3.0, which is the most recent version.  In our local WINS environment we have a campus wide license. During the lab work you will have both the Kernel and the Front End running on your local workstation.

A.1.2 The Notebook Structure, Starting and Using the Kernel

The Notebook

Mathematica supports a special Notebook interface on most computers with a graphical user interface. In this section the structure of this Notebook is shortly explained and the Notebook Front End is introduced. Finally the use of the Kernel is explained, by starting the Kernel from the Notebook Front End and telling it that is should calculate 1+1 for us.

Currently you are reading a Mathematica Notebook. A notebook is a file containing text, input to the Kernel, and results of calculations, in textual or graphical form, all organised in a hierarchical way. A Notebook can be viewed as a folded piece of paper, which  can be unfolded at will. The folds in the file are called cells. Cells can enclose other cells, and may be opened or closed at will. The cell structure can be controlled by the vertical brackets on the right of this window. The hierarchical structure of a cell group is indicated by the layering of the cell brackets.

Mathematica groups cells automatically on the basis of the cell styles (unless you turn this off, using the Cell Grouping features in the Cell menu). For instance, a subsection is automatically grouped with text cells below the subsection cell, as drawn below. The text cell and Sub Section cell are both enclosed by a bracket, and one level up, again by a next bracket, indicating that both cells are grouped. As you see on the right of this Notebook, there are more than just two brackets, indicating higher levels of grouping of the cells.

[Graphics:Images/appendix_gr_2.gif]

Using the concept of cells containing certain types of information and grouping of cells, we can now take a look on folding up, or closing the cells. A closed cell is marked by an arrow at the bottom of the grouping bracket. By double clicking on such bracket, the closed group is opened, i.e. unfolded, and the contents is shown. Below, an example of such a closed cell is shown. Now open this cell and continue reading inside that cell.

[Graphics:Images/appendix_gr_3.gif]

a closed cell

This is an example of a closed cell (which off-course you just opened), containing text and some graphical output. Under the Style submenu in the Format menu you can assess the style of each specific cell. If you select the cell that you are currently reading, by clicking inside the cell or selecting the cell bracket (click on it once), and look into the Style submenu you will notice that it has the style Text. As you see, the Front End has a large number of predefined cell styles. If you start using the Notebook for the lab exercises you can experiment with the cell styles to create nicely formatted Notebooks, which can be handed over as lab journals. Also notice the StyleSheet submenu in the Format menu which has a large collection of predifined style sheets. Now find out about the cell styles of the three cells you see below. Also notice the special bracket symbols used for these cells.

[Graphics:Images/appendix_gr_4.gif]

[Graphics:Images/appendix_gr_5.gif]

It will by now be clear that you can also close cell groups by double clicking on the enclosing brackets. Note that if you do so, only the head cell of the closed group is visible. In the rest of this Notebook all sections and subsections are closed cells. To read them they should be opened. Closing all sections and subsection (you could do that now) results in an overview of the contents of the Notebook. You can use the Notebook to write your own (interactive, as will become clear later on) lab journals.

The contents of (text) cells can be edited as usual (i.e. inserting text, copying, cutting, pasting, etc., see the Edit menu). Complete (grouped) cells can also be copied and pasted in a Notebook. First, select the cell you want to copy by clicking its enclosing bracket, then choose Copy from the Edit menu, move the cursor to the place where you want to paste the cell. This can only be at places where the cursor changes in a horizontal bar, click (a horizontal line appears), and choose Paste from the Edit menu. As an exercise, try to copy this complete cell to another position in the Notebook.

More on Cell Properties

The properties of Cells control the display of material in your notebook, and also tell Mathematica how to treat particular cells when you perform an evaluation. Cell properties are controlled through the FormatType sub menus and the Cell Properties sub menu under the Cell menu. One of the most important properties of a cell is how it is formatted and if you can edit the cell. For instance, if you select this cell, and look under the Display As sub menu  you will notice that this cell is displayed as text. We will returrn to the FormatType of cells if we discuss Input and Output in Notebooks in more detail in section 1.4.

The cell below is graphical output from Mathematica. Such output is generated by the Kernel as postscript, and the Front End renders it. You can see the underlying postscript code by selecting the cell, and choosing Show Expression from the Format menu. Actually, just before the postscript code you see some Mathematica functions, which are used by the Front End to display the total cell in a correct way. Actually, the overall notebook file is a plain Ascii file only containing such code. In this way the notebooks are fully portable among different computers. Choosing  Show Expression once more brings back the rendered picture.

[Graphics:Images/appendix_gr_6.gif]

A cell can either be Evaluatable or not (as is seen in the Cell Properties sub menu). An evaluatable cell is one that can be evaluated by the Mathematica Kernel, and usually contains mathematical expressions. Non-evaluatable cells contain material that you would ordinarily not want to evaluate, such as explanatory text (as in this cell), as well as Mathematica output. Non-evaluatable cells are marked with a horizontal tick mark near the top of their cell brackets, like the bracket of this cell.

Below is an example of an evaluatable cell, which is recognised by the plain bracket with the little triangle in the top. Checking the Style sub menu shows that it has the style Input. Also look at the cell properties. To evaluate the expression in the input cell (in this case 1+1) you select the cell, or click somewhere in the cell. Then, select from the Kernel menu Evaluation and Evaluate Cells, or faster, just press Shift-Return. As this is your first evaluation, the Mathematica Kernel is not running. So, after you pressed Shift-Return the Mathematica Kernel automatically starts up (this may take a while). For next evaluation the Kernel is already running. Next, the expression in the cell is sent to the Kernel, which evaluates it and sends the result back to the Front End. New cells below the input cells will be created automatically to place the results. Ok, just try to do this!

[Graphics:Images/appendix_gr_7.gif]
[Graphics:Images/appendix_gr_8.gif]

You should notice a few things. First, Mathematica assigns in sequence a number to each of the cells it evaluates, which is useful to address previous results in a longer calculation. Next, the output cell that was created automatically, and the input and output are automatically grouped. Notice again the bracket for the output cell. Now that you know about addition, try to enter, immediately below this cell, another expression (using the symbols *, /, or +) and evaluate it. Just move the cursor down, until it becomes a horizontal bar, click (now you see a line) and start typing your expression. Notice that by default the cell style is an evaluatable input cell. Notice also how Mathematica keeps track of the numbers of evaluations, how the output is organised, and play around with the difference between formatted and unformatted output.

Now you know how to use Mathematica as a calculator. In section 1.3 you will find some useful information about the on-line help facilities in Mathematica. In the following sections you will examine the mathematical and graphical capabilities, and also take a look at programming capabilities of Mathematica.

A.1.3 Getting help in Mathematica

As will become clear Mathematica is a very large system, containing an enormous amount of functions (in the order of 1000). Furthermore, the Front End has many features. All information can of course be found in the user manuals and the Mathematica book (that will be present during lab hours). However, Mathematica has an extensive on-line help facility, which will be of utmost importance to help you through this lab work. A full listing of the syntax and use of all functions and add-on packages is available. Extensive demos and tours through Mathematica are available, and the full Mathematica 3 book is available on-line. However, another very useful help facility is Why the Beep? If something goes wrong, Mathematica will beep. To find out what happened, choose the Why the Beep? command from the Help menu....

The Mathematica Help Browser will become an important companion for you. Choose Help in the Help menu. The help browser now pops up. You can get information from 6 different sources,

Built-in Functions
Getting Started/Demos
Add-ons
Other Information
The Mathematica Book
Master Index

By clicking the radio buttons you select the appropriate source. The Built-in Functions explains Mathematica functions. Add-ons gives access to all standard Mathematica Packages. The Getting Started/Demos gives a wealth of information beyond what is covered in this Lab Work and is helpful as background reading. Other Information fully explains all Menu Commands of the Front End, and gives some other very useful information in using the Front End efficiently. The Mathematica book is the on-line version of the 1400 pages Mathematica 3 book. All you need to know, and much more, is in there. To look up a specific function, start typing its name in the Go To box, or type the function name in a notebook cell, select the function name (e.g. by doubl -clicking on it), and select Find in Help from the Help menu. The Help Browser is a very useful tool when working with Mathematica.

As an exercise, you want to calculate the logarithm to base 10 of 2.5, but forget the function name in Mathematica. You know that the logarithm is an elementary mathematical function. Use the help browser to find the correct function name and calculate the result (which is 0.39794).

• See also the Mathematica book:  Section 1.3.8.

The blue thing is a hyperlink, just click it as you know from Web Browsers. They operate the same.

A.1.4 Input and Output in Notebooks

A.1.4.1 Introduction

In previous versions of Mathematica all input was purely text based and in terms of functions. For instance, to calculate a variable x to the power 2 would be expressed as

Power[x,2]
[Graphics:Images/appendix_gr_9.gif]

or in shorthand, as

x^2
[Graphics:Images/appendix_gr_10.gif]

The output is shown below.

      2
     x

The format of both input cells above is InputForm as can be assessed from the Display As sub menu from the Cell menu. The output is in OutputForm, as can be seen in the Convert To sub menu from the Cell menu. Also, more complicated formula can be built up using this InputForm and OutputForm. An example is shown below.

(x^2 + y^6 - Sqrt[z])/(x^3 + z^2)
[Graphics:Images/appendix_gr_11.gif]

Of course, for many mathematical functions a standard mathematical notation exists, which is probably easier to use. Furthermore, if you are working with formula manipulations and you want to print or publish the results you also want to have nicely formatted formulas, according to the accepted standards. In Mathematica 3 this is possible, and is the default way of entering mathematical formulas (although the fully text based approach in the InputForm and OutputForm can also still be used).

Below you now see the examples from above in nice mathematical notation.

[Graphics:Images/appendix_gr_12.gif]
[Graphics:Images/appendix_gr_13.gif]
[Graphics:Images/appendix_gr_14.gif]
[Graphics:Images/appendix_gr_15.gif]

The format of the input and output cells is now StandardForm. Notice the difference in brackets between the InputForm and OutputForm formats and the StandardForm formats. Look at the different brackets as compared to the InputForm and OutputForm formats. By default, your input and output will be in StandardForm. This can be controlled by the  Default sub menus from the Cell menu. However, we advise you not to change these settings.

Besides the differences in look, the use of the StandardForm has another important advantage. Both the input and the output can be edited. In OutputForm, the output cannot be edited. This is important if you want to build up calculations. For instance, just try to edit the output of the last example, by changing [Graphics:Images/appendix_gr_16.gif]to [Graphics:Images/appendix_gr_17.gif](just select the 2 and change it into a 3).  Notice what happens, the original output is automatically copied into a new cell, and your changes are effectuated in that cell. You can now evaluate the new cell.

Finally, Mathematica knows another format, the so-called TradionalForm. This format tries to imitate all aspects of traditional mathematical notation. It's great if you want to produce printing quality Notebooks. However, for normal use we advise to stick to the StandardForm. Below is an example of the previous formula in TraditionalForm.

[Graphics:Images/appendix_gr_18.gif]

• See also the Mathematica book:  Section 1.10.9.

A.1.4.2 Palettes

The easiest way to organise the input of mathematical formula, Greek letters, matrices, etc. is through the use of Palettes. Under the File menu choose from the  Palettes sub menu BasicInput. You now see a palette window containing a number of buttons with predefined templates. By pressing the buttons the template is copied into the cell, and you can further edit the template to the final expression. Below is an example. Try to reproduce this formula in an input cell, and evaluate it.

[Graphics:Images/appendix_gr_19.gif]

Notice that the templates work in such a way that if you already entered an expression, and if you select (part of) that expression, it is automatically pasted into the black position of the template. Experiment a little bit with the Palettes. Also take a look at the other Palettes. Finally, shift between the StandForm and the InputForm to see the underlying functions.

• See also the Mathematica book:  Section 1.10.1., Section 1.10.2, Section 1.10.3, Section 1.10.4, Section 1.10.5, Section 1.10.6, Section 1.10.7, Section 1.10.8.

A.1.5 Repairing corrupted Notebooks

It has happened to a few students that their report couldn't be read by Mathematica after they had saved their work. Most often the cause of this is that Mathematica doesn't check whether you have passed your disk quotum. So please, always keep an eye on your disk usage. In any case, always make sure that you have a backup of your work, and that you save your work regularly. The safest strategy is to make a backup of your last version before starting Mathematica and making any changes:
cp notebook.nb notebook.bak
If something goes wrong if you save your work, during which you are overwriting your most recent version, at least you still have your backup. If, despite all your precautions, your file has been damaged, it may be possible to repair it. The following website contains a Mathematica package and an explanation that may help you to repair your work. [Graphics:Images/appendix_gr_20.gif]

A.2 Try this!

As an appetiser, and before entering into a less interesting (but on the other hand important to know) section on notational conventions, a first glimpse at the power of Mathematica is shown. More details and other functions are described in sections 4 and 5. Play around with what you see, find out more about these functions using the help browser, and do not hesitate to experiment with the functions! The motto in this lab work is "learning by doing"! To save (your) time, the input is already typed into input cells. All you need to do is evaluate the cells, see what happens, and learn from that.

Let us start with calculating 100 x 99 x 98 x ... x 2 x 1

[Graphics:Images/appendix_gr_21.gif]
[Graphics:Images/appendix_gr_22.gif]

Notice that Mathematica returns the exact result, something that your pocket calculator will not do. By the way, the "!" is just (well-known) shorthand for the function Factorial.

[Graphics:Images/appendix_gr_23.gif]
[Graphics:Images/appendix_gr_24.gif]

Usually it takes a lot of time to do lengthy algebraic calculation by hand, such as e.g. calculating (1+x) to the power 20. How much time would you need for that? Now let us see how Mathematica deals with that.

[Graphics:Images/appendix_gr_25.gif]
[Graphics:Images/appendix_gr_26.gif]

Feel like checking this result? Maybe you should try to do some simpler examples.

Do you hate doing integrals? Again, Mathematica is good at it. For instance, here is how to calculate the indefinite integral of (1+x)/(1-x)

[Graphics:Images/appendix_gr_27.gif]
[Graphics:Images/appendix_gr_28.gif]

To convince yourself of the answer, also do the integral by hand. Now differentiate the previous result (note that the % refers to the last obtained result) ...

[Graphics:Images/appendix_gr_29.gif]
[Graphics:Images/appendix_gr_30.gif]

...and simplify the result...

[Graphics:Images/appendix_gr_31.gif]
[Graphics:Images/appendix_gr_32.gif]

... resulting in the original expression.

Mathematica has many graphical functions (see more on this in chapter 4 and 5). As a start, look at this one dimensional plot ...

[Graphics:Images/appendix_gr_33.gif]

[Graphics:Images/appendix_gr_34.gif]

... and an example of three dimensional plotting. Notice the use of options (such as PlotPoints) to control the behaviour of the function Plot3D.

[Graphics:Images/appendix_gr_35.gif]

[Graphics:Images/appendix_gr_36.gif]

A.3 Notational Conventions

A.3.1 Built-In Names

The names of all functions, variables, options, and constants built into Mathematica start with capital letters, e.g. Integrate, Plot. If a name consists of two or more words, the first letter of each word is capitalised, e.g. PlotPoints.

Most names of objects built into Mathematica are complete words. Unlike Unix, MS-DOS, and other systems, Mathematica rarely uses abbreviations. Abbreviations are used only where they are extremely well-known. The following table contains examples of some of the abbreviations that are built into Mathematica.

Abs    gives the absolute value of a number
Cos    gives the trigonometric function cosine
D      
computes the derivative
Det    
calculated the determinant of a matrix
GCD    
computes the greatest common divisor

There are in the order of 1000 functions built into Mathematica. The names of the functions in general indicate the function's purpose. As an example, look at the following function names.

Eigenvalues    gives a list of eigenvalues
FindRoot       searches for a numerical solution to an equation
Integrate      
evaluates the integral
Timing         
returns the time used in evaluating an expression

A.3.2 Mathematical Notation

Typically Mathematica uses English words. Most people are used to referring to standard mathematical functions with symbols rather than words, i.e. symbols such as +, -, *, /, <, and > rather than the words Plus, Minus, Times, Divide, Less, and Greater. The following table contains some of the mathematical symbols supported in Mathematica (in InputForm).

+    Plus
-    Minus, Subtract
*    
Times
/    
Divide
^    
Power
!    Factorial
<    Less
<=   
LessEqual
>    
Greater
>=   
GreaterEqual

In mathematical notation, the product of a and c is commonly written as a c. Mathematica also understands this notation. The asterisk * denoting multiplication is optional. A blank character or space also denotes multiplication.

A.3.3 Brackets

Be aware that Mathematica has adopted slightly different conventions from C, Pascal, and Fortran. Parentheses are used for grouping, a single set of square brackets is used for calling or specifying functions and braces are used for lists, vectors, and matrices. Here is a summary of the different types of brackets.

bracket                    Purpose                                             Examples

(
term)        Grouping                  (a + b)/(c + d)
f[expr]       Arguments of function         Sin[2 Pi x]
{
a,b,c}       Vectors, matrices, and lists      {x, 2 x, 3 x}
v[[
i]]        Indexing                   m[[3]], m[[1,2]]
(*
remark *)  Commenting                (* watch out *)

A.3.4 Using Previous Results

Here is a result.

[Graphics:Images/appendix_gr_37.gif]
[Graphics:Images/appendix_gr_38.gif]

The percent sign (%) gives the previous result. This input multiplies the previous result by 3.

[Graphics:Images/appendix_gr_39.gif]
[Graphics:Images/appendix_gr_40.gif]

Out[n] or %n gives output n.

A.4 Using Mathematica

A.4.1 A next look at Graphics in Mathematica

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

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

[Graphics:Images/appendix_gr_41.gif]

[Graphics:Images/appendix_gr_42.gif]

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.

[Graphics:Images/appendix_gr_43.gif]

[Graphics:Images/appendix_gr_44.gif]

Notice how the option AxesLabel effects the graph. Here is the same graph with a label.

[Graphics:Images/appendix_gr_45.gif]

[Graphics:Images/appendix_gr_46.gif]

For a complete list of the options available for Plot3D use the help browser.

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, is slightly beyond the usual graphing done by hand in a calculus course.

[Graphics:Images/appendix_gr_47.gif]

[Graphics:Images/appendix_gr_48.gif]

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

[Graphics:Images/appendix_gr_49.gif]

[Graphics:Images/appendix_gr_50.gif]

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

[Graphics:Images/appendix_gr_51.gif]

[Graphics:Images/appendix_gr_52.gif]

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.

[Graphics:Images/appendix_gr_53.gif]

[Graphics:Images/appendix_gr_54.gif]

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

[Graphics:Images/appendix_gr_55.gif]

[Graphics:Images/appendix_gr_56.gif]

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

[Graphics:Images/appendix_gr_57.gif]

[Graphics:Images/appendix_gr_58.gif]

[Graphics:Images/appendix_gr_59.gif]

By the way, notice the use of two evaluations in one cell (the Plot and Show command) and how Mathematica organises the output.

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

[Graphics:Images/appendix_gr_60.gif]

[Graphics:Images/appendix_gr_61.gif]

We return to surface graphs for a final example. Many surfaces cannot be described as a graph of a function [Graphics:Images/appendix_gr_62.gif].  A hyperboloid of 1 sheet is an example of such a surface. In order to graph these surfaces, you need to 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

[Graphics:Images/appendix_gr_63.gif]

[Graphics:Images/appendix_gr_64.gif]

This example also showed how you can define your own functions in Mathematica. We will return to this point later.

A.4.2 Algebraic 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

[Graphics:Images/appendix_gr_65.gif]
[Graphics:Images/appendix_gr_66.gif]

and

[Graphics:Images/appendix_gr_67.gif]
[Graphics:Images/appendix_gr_68.gif]

Yielding a formula in a much simpler form.

Differentiation and integration are also built-in operations:

[Graphics:Images/appendix_gr_69.gif]
[Graphics:Images/appendix_gr_70.gif]
[Graphics:Images/appendix_gr_71.gif]
[Graphics:Images/appendix_gr_72.gif]
[Graphics:Images/appendix_gr_73.gif]
[Graphics:Images/appendix_gr_74.gif]
[Graphics:Images/appendix_gr_75.gif]
[Graphics:Images/appendix_gr_76.gif]

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.

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.

[Graphics:Images/appendix_gr_77.gif]
[Graphics:Images/appendix_gr_78.gif]

Series can also handle purely symbolic functions such as f.

[Graphics:Images/appendix_gr_79.gif]
[Graphics:Images/appendix_gr_80.gif]

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

[Graphics:Images/appendix_gr_81.gif]
[Graphics:Images/appendix_gr_82.gif]

A.4.3 Numerical Calculations

A first Look

You can do arithmetic with Mathematica, just as you would on a calculator. You have seen some examples in previous chapters. However, you must realise that Mathematica can give you exact results. So, let's calculate the exact result for 3 to power 1000.

[Graphics:Images/appendix_gr_83.gif]
[Graphics:Images/appendix_gr_84.gif]

You can use the Mathematica function N to get approximate results.

[Graphics:Images/appendix_gr_85.gif]
[Graphics:Images/appendix_gr_86.gif]

As an exercise, find the square root of 10 to 8 digits precision (the answer is 3.1622777). Remember, the help browser answers all your questions how to do this.

Mathematica can also handle complex numbers. In Mathematica I stands for the imaginary number.

[Graphics:Images/appendix_gr_87.gif]
[Graphics:Images/appendix_gr_88.gif]
[Graphics:Images/appendix_gr_89.gif]
Some Mathematical Functions

The following mathematical functions are given without explanation.

N[]
Sqrt[x]
Exp[x]
Log[x]
Log[b,x]
Sin[x], Cos[x], Tan[x]
ArcSin[x], ArcCos[x], ArcTan[x]
Abs[x]
Round[x]
Mod[n, m]
Random[]
Max[x, y, ...], Min[x, y, ...]
FactorInteger[n]
RealDigits[r]
IntegerDigits[n]

The following constants are built into Mathematica .

Pi
E
Degree
I
Infinity

Here are some examples:

[Graphics:Images/appendix_gr_90.gif]
[Graphics:Images/appendix_gr_91.gif]
[Graphics:Images/appendix_gr_92.gif]
[Graphics:Images/appendix_gr_93.gif]
[Graphics:Images/appendix_gr_94.gif]
[Graphics:Images/appendix_gr_95.gif]
[Graphics:Images/appendix_gr_96.gif]
[Graphics:Images/appendix_gr_97.gif]
[Graphics:Images/appendix_gr_98.gif]
[Graphics:Images/appendix_gr_99.gif]
[Graphics:Images/appendix_gr_100.gif]
[Graphics:Images/appendix_gr_101.gif]
Assigning values to variables

This sets x to be 5

[Graphics:Images/appendix_gr_102.gif]
[Graphics:Images/appendix_gr_103.gif]

The x may now be used in calculations and will have the value 5.

[Graphics:Images/appendix_gr_104.gif]
[Graphics:Images/appendix_gr_105.gif]

This redefines the value for x.

[Graphics:Images/appendix_gr_106.gif]
[Graphics:Images/appendix_gr_107.gif]

Asking for x gives the current value of x.

[Graphics:Images/appendix_gr_108.gif]
[Graphics:Images/appendix_gr_109.gif]

Clear[x] or x = . clears the value for x.

[Graphics:Images/appendix_gr_110.gif]

The result of the input x will now be x.

[Graphics:Images/appendix_gr_111.gif]
[Graphics:Images/appendix_gr_112.gif]

A common source of problems in using Mathematica is trying to use variables that already have values assigned. Therefore, clear variables directly after you are finished with them or before you use them.

Because Mathematica functions begin with capital letters, you may wish to begin your own function names with lower case letters to prevent confusion.

Suppressing Output

Output can be suppressed by using semicolons after expressions. Semicolons can also be used to separate statements on a line.

[Graphics:Images/appendix_gr_113.gif]
[Graphics:Images/appendix_gr_114.gif]
[Graphics:Images/appendix_gr_115.gif]
More Powerful Numerical Capabilities

Mathematica can evaluate all standard mathematical functions. Here is the value of the Bessel function of zeroth order of 14.5.

[Graphics:Images/appendix_gr_116.gif]
[Graphics:Images/appendix_gr_117.gif]

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.

[Graphics:Images/appendix_gr_118.gif]
[Graphics:Images/appendix_gr_119.gif]

And you can factor integers as in

[Graphics:Images/appendix_gr_120.gif]
[Graphics:Images/appendix_gr_121.gif]

How should the output be interpreted ?

Remember integration from section 2? Try to compute the exact value of the definite integral of
[Graphics:Images/appendix_gr_122.gif][Graphics:Images/appendix_gr_123.gif]on the interval {x, 0, 3π/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.

[Graphics:Images/appendix_gr_124.gif]
[Graphics:Images/appendix_gr_125.gif]

What about the accuracy of NIntegrate. If you have time left, try to find it experimentally, and compare with the default setting of NIntegrate?

A.4.4 Solving Equations

Here is an algebraic equation in Mathematica

[Graphics:Images/appendix_gr_126.gif]
[Graphics:Images/appendix_gr_127.gif]

This solves the equation on the previous line and gives the solution in terms of the parameter a.

[Graphics:Images/appendix_gr_128.gif]
[Graphics:Images/appendix_gr_129.gif]

Here is the solution to a simple set of simultaneous equations.

[Graphics:Images/appendix_gr_130.gif]
[Graphics:Images/appendix_gr_131.gif]

Mathematica can also solve differential equations. Here is the closed form solution for [Graphics:Images/appendix_gr_132.gif].

[Graphics:Images/appendix_gr_133.gif]
[Graphics:Images/appendix_gr_134.gif]

Mathematica also solves equations numerically. If you would try to solve the equation [Graphics:Images/appendix_gr_135.gif], you would find

[Graphics:Images/appendix_gr_136.gif]

which means that Mathematica could not find an explicit algebraic form, and leaves the results in a symbolic form.

Note that the syntax above is further explained in section 1.4.8

Applying N gives the numerical results

[Graphics:Images/appendix_gr_137.gif]
[Graphics:Images/appendix_gr_138.gif]
[Graphics:Images/appendix_gr_139.gif]
[Graphics:Images/appendix_gr_140.gif]

If you are only interested in numerical results, it is usually a lot faster to use the function NSolve to ask for a numerical results.

[Graphics:Images/appendix_gr_141.gif]
[Graphics:Images/appendix_gr_142.gif]

NSolve gives you a general way to find numerical approximations to the solutions of polynomial equations. Finding numerical solutions to more general equations, however, can be much more difficult. FindRoot gives you a way to search for a numerical solution to an arbitrary equation, or set of equations. Below is an example how FindRoot allows you to solve transcendental equation numerically. This gives the solution to a pair of simultaneous equations near [Graphics:Images/appendix_gr_143.gif].

[Graphics:Images/appendix_gr_144.gif]
[Graphics:Images/appendix_gr_145.gif]

As you would expect by now, Mathematica can also find numerical solutions to differential equations. Below, NDSolve solves for the function y with x in the range 0 to 20.

[Graphics:Images/appendix_gr_146.gif]
[Graphics:Images/appendix_gr_147.gif]

The solution is given as an interpolating function, which allows to find values of y(x) for specific values of x. Below we take the solution and plot it as a function of x.

[Graphics:Images/appendix_gr_148.gif]

[Graphics:Images/appendix_gr_149.gif]

Intermezzo, the /. Construction, Applying Transformation Rules

When transforming an expression like [Graphics:Images/appendix_gr_150.gif]to [Graphics:Images/appendix_gr_151.gif] , Mathematica treats [Graphics:Images/appendix_gr_152.gif] in a purely symbolic manner. One way to replace [Graphics:Images/appendix_gr_153.gif] with a definite value is to apply a transformation rule.

This is how you apply a transformation rule. You can think of this as "in the expression [Graphics:Images/appendix_gr_154.gif] replace all [Graphics:Images/appendix_gr_155.gif] with 3."

[Graphics:Images/appendix_gr_156.gif]
[Graphics:Images/appendix_gr_157.gif]

You can replace x with an expression.

[Graphics:Images/appendix_gr_158.gif]
[Graphics:Images/appendix_gr_159.gif]

You can apply lists of rules.

[Graphics:Images/appendix_gr_160.gif]
[Graphics:Images/appendix_gr_161.gif]

More information on transformation rules is given in section 4.6.

A.4.5 Lists and Matrices

Making Lists of Objects

Lists are a way to make collections of objects in Mathematica. Lists are important structures in Mathematica.

Here is a list of three numbers.

[Graphics:Images/appendix_gr_162.gif]
[Graphics:Images/appendix_gr_163.gif]

You can perform arithmetic operations on the whole list.

[Graphics:Images/appendix_gr_164.gif]
[Graphics:Images/appendix_gr_165.gif]

This takes the difference between corresponding elements in the lists. The
lists must be of equal length.

[Graphics:Images/appendix_gr_166.gif]
[Graphics:Images/appendix_gr_167.gif]

You can apply mathematical functions to whole lists.

[Graphics:Images/appendix_gr_168.gif]
[Graphics:Images/appendix_gr_169.gif]

You can assign the list to a variable.

[Graphics:Images/appendix_gr_170.gif]
[Graphics:Images/appendix_gr_171.gif]

This variable ll can be used instead of the list in subsequent calculations.

[Graphics:Images/appendix_gr_172.gif]
[Graphics:Images/appendix_gr_173.gif]
Manipulating Elements of Lists

You can refer to parts of lists by using double brackets or Part.

This takes the first element in the list.

[Graphics:Images/appendix_gr_174.gif]
[Graphics:Images/appendix_gr_175.gif]

Notice the use of the [Graphics:Images/appendix_gr_176.gif] symbols in the StandardForm, which in InputForm would be just double brackets, as was explained in section A.3.3.

This extracts a list of elements.

[Graphics:Images/appendix_gr_177.gif]
[Graphics:Images/appendix_gr_178.gif]

You can reset the value of elements in a list. Here is a list assigned to w.

[Graphics:Images/appendix_gr_179.gif]
[Graphics:Images/appendix_gr_180.gif]

This resets the value of the 5th element in the list to b.

[Graphics:Images/appendix_gr_181.gif]
[Graphics:Images/appendix_gr_182.gif]
[Graphics:Images/appendix_gr_183.gif]
[Graphics:Images/appendix_gr_184.gif]
[Graphics:Images/appendix_gr_185.gif]
Making Tables of Values

The following command makes a list of the squares of the first twenty positive integers.

[Graphics:Images/appendix_gr_186.gif]
[Graphics:Images/appendix_gr_187.gif]

Next, we plot the values in the list

[Graphics:Images/appendix_gr_188.gif]

[Graphics:Images/appendix_gr_189.gif]

You can specify the stepsize:

[Graphics:Images/appendix_gr_190.gif]
[Graphics:Images/appendix_gr_191.gif]

You can read data from an external file (notice that file example.dat must be accessible).

[Graphics:Images/appendix_gr_192.gif]
[Graphics:Images/appendix_gr_193.gif]

You can also make lists like this:

[Graphics:Images/appendix_gr_194.gif]
[Graphics:Images/appendix_gr_195.gif]

The next command generates a 2D matrix whose (i,j)-entry equals the greatest common divisor of i and j.

[Graphics:Images/appendix_gr_196.gif]
[Graphics:Images/appendix_gr_197.gif]

You can manipulate matrices and lists all at the time

[Graphics:Images/appendix_gr_198.gif]
[Graphics:Images/appendix_gr_199.gif]

You can access parts of the list using double brackets or Part.

[Graphics:Images/appendix_gr_200.gif]
[Graphics:Images/appendix_gr_201.gif]
[Graphics:Images/appendix_gr_202.gif]
[Graphics:Images/appendix_gr_203.gif]

Or write it like this

[Graphics:Images/appendix_gr_204.gif]
[Graphics:Images/appendix_gr_205.gif]
[Graphics:Images/appendix_gr_206.gif]

A range of points

[Graphics:Images/appendix_gr_207.gif]
[Graphics:Images/appendix_gr_208.gif]

I want only the first elements

[Graphics:Images/appendix_gr_209.gif]
[Graphics:Images/appendix_gr_210.gif]

Or

[Graphics:Images/appendix_gr_211.gif]
[Graphics:Images/appendix_gr_212.gif]

Remember the command Table, as it is very useful for future work. If you want the list to look more like a matrix you can use the command

[Graphics:Images/appendix_gr_213.gif]
[Graphics:Images/appendix_gr_214.gif]

We can compute the determinant of the matrix with

[Graphics:Images/appendix_gr_215.gif]
[Graphics:Images/appendix_gr_216.gif]

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

[Graphics:Images/appendix_gr_217.gif]
[Graphics:Images/appendix_gr_218.gif]

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

[Graphics:Images/appendix_gr_219.gif]
[Graphics:Images/appendix_gr_220.gif]

Mathematica can also manipulate symbolic matrices. This finds the eigenvectors of a matrix, then simplifies the algebraic result.

[Graphics:Images/appendix_gr_221.gif]
[Graphics:Images/appendix_gr_222.gif]

Here's a list of other Mathematica functions which work with matrices and lists.

Array[a,n] or Array[a, {n,m}]
Range[n]
Length[list]
ColumnForm[list]
Dimensions[list]
MatrixForm[list]
MatrixPower[m,n]
Inverse[m]
Det[m]
Transpose[m]
Eigenvectors[m]
Eigenvalues[m]

Getting Parts of Lists

Here are some functions to use for taking parts of lists.

First[list]
Last[list]
Part[list,n]
Take[list,n]
Rest[list]
Drop[list,n]

Rearranging Lists

Some functions for rearranging lists

Sort[list]
Union[list]
Reverse[list]
RotateLeft[list,n]
RotateRight[list,n]

A.4.6 More on Transformation Rules

You have already seen how to use a rule, for instance [Graphics:Images/appendix_gr_223.gif] on a algebraic expression.

[Graphics:Images/appendix_gr_224.gif]
[Graphics:Images/appendix_gr_225.gif]

You can give transformation rules for any expression. Here's a rule for [Graphics:Images/appendix_gr_226.gif].

[Graphics:Images/appendix_gr_227.gif]
[Graphics:Images/appendix_gr_228.gif]

More general, this replace [Graphics:Images/appendix_gr_229.gif], where anything is named [Graphics:Images/appendix_gr_230.gif], by [Graphics:Images/appendix_gr_231.gif].

[Graphics:Images/appendix_gr_232.gif]
[Graphics:Images/appendix_gr_233.gif]

Here is a Mathematica function definition, specifying that [Graphics:Images/appendix_gr_234.gif] is always to be transformed to [Graphics:Images/appendix_gr_235.gif].

[Graphics:Images/appendix_gr_236.gif]
[Graphics:Images/appendix_gr_237.gif]
[Graphics:Images/appendix_gr_238.gif]

Using the question mark gives information about the rules you have defined for a function.

[Graphics:Images/appendix_gr_239.gif]
Global`f
[Graphics:Images/appendix_gr_240.gif]

Actually, the question mark also provides information on build-in functions

[Graphics:Images/appendix_gr_241.gif]
[Graphics:Images/appendix_gr_242.gif]

Here is a way to get extra information including Attributes and Options.

[Graphics:Images/appendix_gr_243.gif]
[Graphics:Images/appendix_gr_244.gif]
[Graphics:Images/appendix_gr_245.gif]
[Graphics:Images/appendix_gr_246.gif]

You can also use wild cards.

[Graphics:Images/appendix_gr_247.gif]
[Graphics:Images/appendix_gr_248.gif]
[Graphics:Images/appendix_gr_249.gif] [Graphics:Images/appendix_gr_250.gif] [Graphics:Images/appendix_gr_251.gif] [Graphics:Images/appendix_gr_252.gif] [Graphics:Images/appendix_gr_253.gif]
[Graphics:Images/appendix_gr_254.gif] [Graphics:Images/appendix_gr_255.gif] [Graphics:Images/appendix_gr_256.gif] [Graphics:Images/appendix_gr_257.gif] [Graphics:Images/appendix_gr_258.gif]
[Graphics:Images/appendix_gr_259.gif] [Graphics:Images/appendix_gr_260.gif] [Graphics:Images/appendix_gr_261.gif] [Graphics:Images/appendix_gr_262.gif]
[Graphics:Images/appendix_gr_263.gif] [Graphics:Images/appendix_gr_264.gif] [Graphics:Images/appendix_gr_265.gif] [Graphics:Images/appendix_gr_266.gif]

Returning to the transformation rules, you can also define recursive rules, e.g. for the factorial function.

[Graphics:Images/appendix_gr_267.gif]

Also provide a rule for the end condition of the function.

[Graphics:Images/appendix_gr_268.gif]

Here are once more the rules you just defined.

[Graphics:Images/appendix_gr_269.gif]
Global`fac
[Graphics:Images/appendix_gr_270.gif]
[Graphics:Images/appendix_gr_271.gif]

Mathematica can now apply these rules to find the value for factorials.

[Graphics:Images/appendix_gr_272.gif]
[Graphics:Images/appendix_gr_273.gif]

Compare the result with the build-in factorial function.

"/." is the operator that can be symbol replacements:

[Graphics:Images/appendix_gr_274.gif]
[Graphics:Images/appendix_gr_275.gif]

or pattern replacements

[Graphics:Images/appendix_gr_276.gif]
[Graphics:Images/appendix_gr_277.gif]

In a pattern replacement rule, x_ means "anything matches here, and call that x".

Mathematica internally holds a list of replacements.

[Graphics:Images/appendix_gr_278.gif]
[Graphics:Images/appendix_gr_279.gif]

This means, that each time Mathematica encounters the symbol "x", it will be replaced by "5".

[Graphics:Images/appendix_gr_280.gif]
[Graphics:Images/appendix_gr_281.gif]

Now, watch the difference between "=" and ":="

[Graphics:Images/appendix_gr_282.gif]
[Graphics:Images/appendix_gr_283.gif]
[Graphics:Images/appendix_gr_284.gif]
[Graphics:Images/appendix_gr_285.gif]
[Graphics:Images/appendix_gr_286.gif]
[Graphics:Images/appendix_gr_287.gif]
[Graphics:Images/appendix_gr_288.gif]
[Graphics:Images/appendix_gr_289.gif]
[Graphics:Images/appendix_gr_290.gif]
[Graphics:Images/appendix_gr_291.gif]
[Graphics:Images/appendix_gr_292.gif]
[Graphics:Images/appendix_gr_293.gif]
[Graphics:Images/appendix_gr_294.gif]

":=" is called the delayed assignment. It means, that the right-hand side will not be evaluated before it is assigned to the left-hand side. In this example "x+5" will be evaluated if you ask for the value of "z". Compare y and z in the  following example:

[Graphics:Images/appendix_gr_295.gif]
[Graphics:Images/appendix_gr_296.gif]
[Graphics:Images/appendix_gr_297.gif]
[Graphics:Images/appendix_gr_298.gif]
[Graphics:Images/appendix_gr_299.gif]

This is important for defining functions:

The following defines a global pattern replacement rule f[x_]->Sin[x]

Compare the following two examples, and watch the role of the delayed assignment :=

[Graphics:Images/appendix_gr_300.gif]
[Graphics:Images/appendix_gr_301.gif]
[Graphics:Images/appendix_gr_302.gif]
[Graphics:Images/appendix_gr_303.gif]
[Graphics:Images/appendix_gr_304.gif]
[Graphics:Images/appendix_gr_305.gif]

But

[Graphics:Images/appendix_gr_306.gif]
[Graphics:Images/appendix_gr_307.gif]
[Graphics:Images/appendix_gr_308.gif]
[Graphics:Images/appendix_gr_309.gif]
[Graphics:Images/appendix_gr_310.gif]

Also, remember to define a pattern replacement rather than a fixed replacement rule. The following is probably not what you want:

[Graphics:Images/appendix_gr_311.gif]
[Graphics:Images/appendix_gr_312.gif]
[Graphics:Images/appendix_gr_313.gif]
[Graphics:Images/appendix_gr_314.gif]

You can also define functions of multiple variables

[Graphics:Images/appendix_gr_315.gif]
[Graphics:Images/appendix_gr_316.gif]
[Graphics:Images/appendix_gr_317.gif]

Note that "overloading" of function names is possible

[Graphics:Images/appendix_gr_318.gif]
[Graphics:Images/appendix_gr_319.gif]
[Graphics:Images/appendix_gr_320.gif]
[Graphics:Images/appendix_gr_321.gif]
[Graphics:Images/appendix_gr_322.gif]

You can also take the derivative like this:

[Graphics:Images/appendix_gr_323.gif]
[Graphics:Images/appendix_gr_324.gif]
[Graphics:Images/appendix_gr_325.gif]
[Graphics:Images/appendix_gr_326.gif]
[Graphics:Images/appendix_gr_327.gif]
[Graphics:Images/appendix_gr_328.gif]
[Graphics:Images/appendix_gr_329.gif]
[Graphics:Images/appendix_gr_330.gif]

A.4.7 Using Add-On Packages

Mathematica  comes with several packages for special applications.  Packages must be loaded into a session before they can be used.
$Packages gives a list of the contexts corresponding to all packages that have been loaded in your current Mathematica session.

The various packages are located in the Packages sub-folder of the Mathematica folder.  Information about them can be found in the book Mathematica Standard Add-On Packages, which is part of the standard Mathematica  distribution, and also in the help browser. Also, the help browser helps in getting information on the available packages. The following example illustrates the use of a package.

[Graphics:Images/appendix_gr_331.gif]

This command loads the package Polyhedra. It reads in a file, evaluating each expression in it, and returning the last one. Now that the package has been loaded, we can use some of the commands defined in the package.

[Graphics:Images/appendix_gr_332.gif]

[Graphics:Images/appendix_gr_333.gif]

You can also use Need command which read in the package if the specified context is not already in $Package. Itt should be used if you want to set it up so that a particular package is read in only if it is needed.
This loads the package PlotField if it has not already been loaded:

[Graphics:Images/appendix_gr_334.gif]

SetDirectory sets the current working directory.  

A.4.8 Programming in Mathematica

Examples

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

p?test is a pattern object that stands for any expression which matches p, and on which the application of test gives True.

[Graphics:Images/appendix_gr_335.gif]
[Graphics:Images/appendix_gr_336.gif]

The definition for p1 applies only when x is manifestly a number.

[Graphics:Images/appendix_gr_337.gif]
[Graphics:Images/appendix_gr_338.gif]

The definition for p2 is more liberal.

[Graphics:Images/appendix_gr_339.gif]
[Graphics:Images/appendix_gr_340.gif]

The following code displays the graphs of a function for several different values of the parameter a.

[Graphics:Images/appendix_gr_341.gif]

[Graphics:Images/appendix_gr_342.gif]

The above example involves 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 enclosing cell bracket, choose the Cell 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. If you close the cell group containing all the graphics you only see the first generated graphic. Double-clicking on the this graphic now suffices to start the animation

If you want to print an animation, of course there is a problem. You could print one frame per page to generate a kind of flip book animation. Or, you could just print several frames per page in some type of matrix arrangement.  The GraphicsArray command makes the latter possible, as illustrated below.

[Graphics:Images/appendix_gr_343.gif]

[Graphics:Images/appendix_gr_344.gif]

If you want to perform an operation many times until some condition is true, you can use While loop:

[Graphics:Images/appendix_gr_345.gif]
[Graphics:Images/appendix_gr_346.gif]
[Graphics:Images/appendix_gr_347.gif]
[Graphics:Images/appendix_gr_348.gif]
[Graphics:Images/appendix_gr_349.gif]

You can often avoid using loops in Mathematica by operating directly on complete lists. The resulting programs are usually more elegant and more efficient. Here are programs to calculate the means and variance of a list. The pattern numlist_List only matches lists.

[Graphics:Images/appendix_gr_350.gif]
[Graphics:Images/appendix_gr_351.gif]
[Graphics:Images/appendix_gr_352.gif]
[Graphics:Images/appendix_gr_353.gif]
[Graphics:Images/appendix_gr_354.gif]
[Graphics:Images/appendix_gr_355.gif]
[Graphics:Images/appendix_gr_356.gif]
[Graphics:Images/appendix_gr_357.gif]
[Graphics:Images/appendix_gr_358.gif]

The final result shows the action of the pattern matching of the numlist_List construction. Mathematica does not have a rule to apply mean to an integer, and therefore returns mean[66]. You could also apply a rule for the case that you give an integer to the function mean.

[Graphics:Images/appendix_gr_359.gif]
[Graphics:Images/appendix_gr_360.gif]
[Graphics:Images/appendix_gr_361.gif]

Here's another example of the use of lists. We will compare the graphs of [Graphics:Images/appendix_gr_362.gif] 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 a number of 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.

[Graphics:Images/appendix_gr_363.gif]

[Graphics:Images/appendix_gr_364.gif]

Finally, here is a program that plots the solutions to a polynomial equation as points in the complex plane. The /; clause at the end checks if [Graphics:Images/appendix_gr_365.gif] is indeed a polynomial if the variable [Graphics:Images/appendix_gr_366.gif]. It fulfills the same function as the pattern matching rules introduced above. Furthermore, notice the use of the /. construction.

[Graphics:Images/appendix_gr_367.gif]
[Graphics:Images/appendix_gr_368.gif]

[Graphics:Images/appendix_gr_369.gif]

And again see the result of check on poly.

[Graphics:Images/appendix_gr_370.gif]
[Graphics:Images/appendix_gr_371.gif]
[Graphics:Images/appendix_gr_372.gif]

Actually, in all these examples you have seen a number of different programming paradigms, supported by Mathematica. In the next parts of this section these different paradigms are listed, and for each an example is presented. This overview, together with the (long) list of programming functions, which you can find in the help browser, gives you a good idea of the very powerful programming capabilities of Mathematica.

Modules

Modules allow you to set up local variables with names that are local to the specific module. The new symbols are created  to represent each of its local variables every time it is called.

This defines the global variable t to have the value 17.

[Graphics:Images/appendix_gr_373.gif]
[Graphics:Images/appendix_gr_374.gif]

The t inside the Module is local, so it can be treated independently of the global t.

[Graphics:Images/appendix_gr_375.gif]
[Graphics:Images/appendix_gr_376.gif]

The global t still has value 17.

[Graphics:Images/appendix_gr_377.gif]
[Graphics:Images/appendix_gr_378.gif]
Blocks and Local Values

Modules in Mathematica allow you to treat the names of variables as local. Sometimes, however, you want the names to be global, but values to be local. You can do this in Mathematica using Block.

Here is an expression involving x.

x^2 + 3
[Graphics:Images/appendix_gr_379.gif]

This evaluates the previous expression, using a local value for x.

Block[{x = a + 1}, %]
[Graphics:Images/appendix_gr_380.gif]

There is no global value for x.

x
[Graphics:Images/appendix_gr_381.gif]

As described  above, the variable x in a module such as Module[[Graphics:Images/appendix_gr_382.gif]x[Graphics:Images/appendix_gr_383.gif], body] is always set up to refer to a unique symbol, different each time the module is used, and distinct from the global symbol x. The x in a block such as Block[[Graphics:Images/appendix_gr_384.gif]x[Graphics:Images/appendix_gr_385.gif], body] is, however, taken to be the global symbol x. What the block does is to make the value of x local. The value x had when you entered the block is always restored when you exit the block. And during the execution of the block, x can take on any value.

Procedural Programming
[Graphics:Images/appendix_gr_386.gif]
[Graphics:Images/appendix_gr_387.gif]
[Graphics:Images/appendix_gr_388.gif]
[Graphics:Images/appendix_gr_389.gif]
List-based Programming
[Graphics:Images/appendix_gr_390.gif]
[Graphics:Images/appendix_gr_391.gif]
[Graphics:Images/appendix_gr_392.gif]
[Graphics:Images/appendix_gr_393.gif]

The next line Flattens out the sublists:

[Graphics:Images/appendix_gr_394.gif]
[Graphics:Images/appendix_gr_395.gif]

The next line partitions into sublists of length 2

[Graphics:Images/appendix_gr_396.gif]
[Graphics:Images/appendix_gr_397.gif]

List based programming is a very handy way to manipulate large amounts of information. To get a feeling of the power of this paradigm, write as, an exercise a procedural program that does the same as in the first example.

[Graphics:Images/appendix_gr_398.gif]
Functional Programming
[Graphics:Images/appendix_gr_399.gif]
[Graphics:Images/appendix_gr_400.gif]

When you use functional operations such as NestList, you always have to specify a function to apply. In the example above, we have used the "name" of a function to specify the function. Pure functions allow you to give functions, which can be applied to arguments without having to define explicit names for the functions.

The red indicates a 'pure function'

[Graphics:Images/appendix_gr_401.gif]
[Graphics:Images/appendix_gr_402.gif]

The # indicates the first variable in a pure function; the & indicates that the preceeding part is the body of a pure function. If you want to define more variables to a pure function you can use #1, #2, etc. You can also define a pure function with Function.

[Graphics:Images/appendix_gr_403.gif]
[Graphics:Images/appendix_gr_404.gif]
[Graphics:Images/appendix_gr_405.gif]
[Graphics:Images/appendix_gr_406.gif]

Technical note : If you are familiar with formal logic or the LISP programming language, you will recognize Mathematica pure functions as being like λ expressions or anonymous functions. Pure functions are also close to the pure mathematical notion of operators.

[Graphics:Images/appendix_gr_407.gif]
[Graphics:Images/appendix_gr_408.gif]

Compile[[Graphics:Images/appendix_gr_409.gif][Graphics:Images/appendix_gr_410.gif], [Graphics:Images/appendix_gr_411.gif], ... [Graphics:Images/appendix_gr_412.gif], expr] creates a compiled function which evaluates expr assuming numerical values of the [Graphics:Images/appendix_gr_413.gif]. You can use Compile[ ... , Evaluate[expr]] to specify that expr should be evaluated symbolically before compilation.

[Graphics:Images/appendix_gr_414.gif]
[Graphics:Images/appendix_gr_415.gif]

Map[f, expr] or f /@ expr applies f to each element on the first level in expr.
and
Map[f, expr, levelspec] applies f to parts of expr specified by levelspec.

Advanced Topic: Rule-based Programming
[Graphics:Images/appendix_gr_416.gif]
[Graphics:Images/appendix_gr_417.gif]
[Graphics:Images/appendix_gr_418.gif]

Notice that Mathematica repeatedly applies the rules it knows to evaluate the expression.

The red stands for any sequence of expressions

[Graphics:Images/appendix_gr_419.gif]
[Graphics:Images/appendix_gr_420.gif]
[Graphics:Images/appendix_gr_421.gif]

To clarify the use of the [Graphics:Images/appendix_gr_422.gif] a little bit further you should realise that the use of a parttern like [Graphics:Images/appendix_gr_423.gif] stands only for instances of the function with exactly two arguments. Sometimes you need to set up patterns that can allow any number of arguments. A double blank, like [Graphics:Images/appendix_gr_424.gif] stands for a sequence of one or more expressions. A triple blank, like [Graphics:Images/appendix_gr_425.gif], stands for a sequence of zero or more expressions

Here is an example of using triple blanks for a rule that picks out pairs of duplicated elements.

[Graphics:Images/appendix_gr_426.gif]
[Graphics:Images/appendix_gr_427.gif]
[Graphics:Images/appendix_gr_428.gif]

You should be very careful whenever you use triple blank patterns. It is easy to make mistakes that lead to an infinite loop (a "livelock"). If  you e.g. define [Graphics:Images/appendix_gr_429.gif], then typing [Graphics:Images/appendix_gr_430.gif] will lead to an infinite loop, with [Graphics:Images/appendix_gr_431.gif] repeatedly matching a sequence with zero elements.

Advanced Topic: Object-oriented Programming

When you make a definition in the form [Graphics:Images/appendix_gr_432.gif] or [Graphics:Images/appendix_gr_433.gif], Mathematica associates your definition with the object [Graphics:Images/appendix_gr_434.gif]. This means, for example, that such definitions are displayed when you type [Graphics:Images/appendix_gr_435.gif]. Mathematica however also supports upvalues, which allow definitions to be associated with symbols that do not appear directly as their head.

Consider for example a definition like Exp[g[x_]] := rhs. One possibility is that this definition could be associated with the symbol Exp, and considered as a downvalue of Exp. This is however not the best thing to do. Better is to consider Exp[g[x_]] := rhs to be associated with [Graphics:Images/appendix_gr_436.gif], and to correspond to an upvalue of [Graphics:Images/appendix_gr_437.gif].

This defines a downvalue for [Graphics:Images/appendix_gr_438.gif].

[Graphics:Images/appendix_gr_439.gif]
[Graphics:Images/appendix_gr_440.gif]
Global`f
[Graphics:Images/appendix_gr_441.gif]

This defines an upvalue for [Graphics:Images/appendix_gr_442.gif].

[Graphics:Images/appendix_gr_443.gif]
[Graphics:Images/appendix_gr_444.gif]
Global`g
[Graphics:Images/appendix_gr_445.gif]

The definition is not associated with Exp.

[Graphics:Images/appendix_gr_446.gif]
[Graphics:Images/appendix_gr_447.gif]

In simple cases, you will get the same answers to calculations whether you give a definition for[Graphics:Images/appendix_gr_448.gif] as a downvalue of an upvalue for [Graphics:Images/appendix_gr_449.gif]. However, one of the two choices is usually much more natural and efficient than the other. A good rule of thumb is that the definition for [Graphics:Images/appendix_gr_450.gif]should be given as an upvalue for [Graphics:Images/appendix_gr_451.gif] in cases where the function [Graphics:Images/appendix_gr_452.gif] is more common than [Graphics:Images/appendix_gr_453.gif].

Upvalues provide a convenient mechanism for specifying how operations act on objects that are tagged to have a certain type. For example, you might want to introduce a class of abstract mathematical objects of type quat. You can represent each object of this type by a Mathematica expression of the form quat[data]. In a typical case, you might want quat objects to have special properties with respect to arithmetic operations such as addition and multiplication. You can set up such properties by defining upvalues for quat with respect to Plus and Times.

This defines an upvalue for quat with respect to Plus (note the other syntax compared to the previous examples, the effect is exactly the same).

[Graphics:Images/appendix_gr_454.gif]
[Graphics:Images/appendix_gr_455.gif]
[Graphics:Images/appendix_gr_456.gif]

When you define an upvalue for quat with respect to an operation like Plus, what you are effectively doing is to extend the domain of the Plus operation to include quat objects. You are telling Mathematica to us special rules for addition in the case where the things to be added are quat objects. In defining addition for quat objects, you could always have a special addition operation, say quatPlus, to which you assign an appropriate downvalue. It is usually much more convenient, however, to use the standard Mathematica Plus operation to represent addition, but then to "overload" this operation by specifying special behaviour when quat objects are encountered.

You can think of upvalues as a way to implement certain aspects of object-oriented programming. A symbol like quat represents a particular type of object. Then the various upvalues for quat specify "methods" that define how quat objects should behave under certain operations, or on receipt of certain "messages".

Advanced Topic: Mixed Programming

Mathematica allows to us all different paradigms in a mixed programming style. Here are some examples. Analyze the examples and try to distinguish between the different programming styles that are used.

[Graphics:Images/appendix_gr_457.gif]
[Graphics:Images/appendix_gr_458.gif]
[Graphics:Images/appendix_gr_459.gif]
[Graphics:Images/appendix_gr_460.gif]
[Graphics:Images/appendix_gr_461.gif]
[Graphics:Images/appendix_gr_462.gif]
Advanced Topic: The Result is Flexibility

Mathematica gives you the flexibility  to write programmes in many different styles:
What follows is 12 ways to define the factorial function:

[Graphics:Images/appendix_gr_463.gif]
[Graphics:Images/appendix_gr_464.gif]
[Graphics:Images/appendix_gr_465.gif]
[Graphics:Images/appendix_gr_466.gif]
[Graphics:Images/appendix_gr_467.gif]
[Graphics:Images/appendix_gr_468.gif]
[Graphics:Images/appendix_gr_469.gif]
[Graphics:Images/appendix_gr_470.gif]
f[n_]:=Fold[Times,1,Range[n]
[Graphics:Images/appendix_gr_471.gif]
[Graphics:Images/appendix_gr_472.gif]
[Graphics:Images/appendix_gr_473.gif]

A.5 Graphics in Mathematica

A.5.1 Introduction

In this section you will further explore the capabilities of Mathematica  for graphing curves in the plane. In addition to graphing functions of a single variable like [Graphics:Images/appendix_gr_474.gif], parametric curves and polar plots will also be explored.

The primary tool for plane graphing is the function Plot. The next section studies this function along with various of its options. After skill with Plot is developed, successive sections examine graphing parametric curves in the plane, using the polar coordinate system, and animating sequences of plane graphs.

Section 5 was completely reproduced from "Graphing in the Plane" by John E. Cruthirds and L. Richard Hitt
Department of Mathematics and Statistics
University of South Alabama.

A.5.2 Using Plot

The Global Behaviour of Functions

Let's look at some examples using the built-in function Plot.

First, we will graph three different fourth degree polynomials with leading coefficient 1.

[Graphics:Images/appendix_gr_475.gif]
[Graphics:Images/appendix_gr_476.gif]

[Graphics:Images/appendix_gr_477.gif]

Technical Note: The use of the Evaluate function is necessary because Plot uses non-standard evaluation of its arguments (as explained in the Mathematica  book). The problem occurs because we did not give the Plot command the list of functions explicitly, but stored the list in a variable. If you like, you can just regard this as an idiom of the Mathematica  language and not be concerned about the details.

Well, there is not much of a pattern to observe on those plots.  Let's widen the interval a little.

[Graphics:Images/appendix_gr_478.gif]

[Graphics:Images/appendix_gr_479.gif]

Notice that more of a pattern becomes apparent.  Finally, let's make the interval very wide.

[Graphics:Images/appendix_gr_480.gif]

[Graphics:Images/appendix_gr_481.gif]

Now the three graphs appear essentially the same. In other words, while the local behaviour of the three given functions was quite different (differing numbers of critical points, inflection points, etc.), the global behaviour of the three functions is essentially the same. You will have a chance to explore the global behaviour of other functions in the exercises at the end of the lab.

The Plot Algorithm

Our goal here is to gain some insight into how the Plot function works. At a simple level, to plot a function, you can just plot a few points and connect them with lines. To do this in Mathematica, you use the graphics primitive Line applied to a list of points. The Graphics function applied to a list of graphics primitives yields a graphics object, which can be viewed with the Show command. For example,

[Graphics:Images/appendix_gr_482.gif]

[Graphics:Images/appendix_gr_483.gif]

Now, let's apply this graphing capability to graph a quadratic function by sampling some of its points and connecting them with line segments.

[Graphics:Images/appendix_gr_484.gif]

[Graphics:Images/appendix_gr_485.gif]

This gives a nice smooth result. The points which were plotted have been emphasised by making them larger than the lines connecting them. Notice that using more points would not significantly improve the plot of the function.  

Let's try another example. This time we will just plot the points without connecting them.

[Graphics:Images/appendix_gr_486.gif]

[Graphics:Images/appendix_gr_487.gif]

That generated a bit of a mess. Let's try using more sample points.

[Graphics:Images/appendix_gr_488.gif]

[Graphics:Images/appendix_gr_489.gif]

Now let's connect the dots and see what we have.

[Graphics:Images/appendix_gr_490.gif]

[Graphics:Images/appendix_gr_491.gif]

That's a little better. However, we have used way too many points on the interval [0,2], and not nearly enough points on the interval [3,5].  What we need is an algorithm which dynamically decides when to use more points to obtain a reasonably accurate rendition of the function.  Well, that's exactly what the Plot function does for us.  Let's try it.

[Graphics:Images/appendix_gr_492.gif]

[Graphics:Images/appendix_gr_493.gif]

This graph gives us a pretty good idea what our function is doing, but there is still room for improving the graph. Notice, for example, that some of the relative extrema on the graph are inaccurate. A closer inspection will show that there is even a missing cycle in the above graph out near [Graphics:Images/appendix_gr_494.gif]. To get a handle on improving the graph, we need to explore some of the options to the Plot function. First, let's list them together with their default values.

[Graphics:Images/appendix_gr_495.gif]
[Graphics:Images/appendix_gr_496.gif]

Three of these options determine how many sample points are used: PlotPoints, PlotDivision, and MaxBend. The value of PlotPoints is the minimum number of points which will be used to construct the graph. In fact, Plot begins by using this number of equally spaced points to sample the function values. If any two consecutive line segments constructed from those sample points produce a "bend" greater than the value of MaxBend (measured in degrees), a subdivision on one of the subintervals will occur. This process continues until all the bends are smaller than MaxBend, or until PlotDivision subdivisions have occurred. This type of algorithm is called an adaptive algorithm. The procedure adjusts the density of sample points according to the needs of the function.

With this in mind, we can try to improve our graph by adjusting some of the options to Plot. Of course, we could always set, for example, PlotDivision->10000 and MaxBend->1, but that would generate a huge number of points and would probably take more time to finish than we were willing to wait. So the goal is to judiciously increase the number of plotted points so that the graph is substantially improved. Certainly we need to increase the value of PlotDivision to allow for more subdivisions on the subintervals when needed. However, because our graph has very low curvature (is almost a straight line) except very near its relative extrema, we should actually be able to increase the value of MaxBend without unduly effecting the accuracy of the graph.  A little trial and error shows that the following values yield a reasonable improvement on our graph.

[Graphics:Images/appendix_gr_497.gif]

[Graphics:Images/appendix_gr_498.gif]

That's great. Compare the above graph with our original attempt using Plot. To aid in the comparison, you can enlarge the graph by clicking on the graph and dragging a corner to increase the size. Notice the improved uniformity on the values of the extrema and the additional cycle near the right end.

To see how many points Mathematica  plotted in the two versions of our graph requires just a bit of work. We need to know a little about the structure of the output of the Plot function in order to tell at what level the information about the actual plotted points is stored. We can get some insight into the structure of the Plot output using the following.

[Graphics:Images/appendix_gr_499.gif]
[Graphics:Images/appendix_gr_500.gif]

If we had entered InputForm without Short, we would get the entire (very) long expression for g1. What we did get is an abbreviated form, where the <<1>> represents a single item -- a long list of points in this case. In fact, it is this list of points we want to know the length of. The <<25>> represents 25 items which have been omitted -- Plot options and their values in this case. In order to find the position of the list containing the point we can detect the level of the Line expression in g1 using

[Graphics:Images/appendix_gr_501.gif]
[Graphics:Images/appendix_gr_502.gif]

The result tells us that the Line command is three levels down in the expression.  So the list of ordered pairs of number is four levels down and the first point in the list is five levels down.  Thus, we try

[Graphics:Images/appendix_gr_503.gif]
[Graphics:Images/appendix_gr_504.gif]

which is the first point used by Plot.

We can now compute the length of the list of pairs of ordered numbers, resulting in the number of points used by Plot.

[Graphics:Images/appendix_gr_505.gif]
[Graphics:Images/appendix_gr_506.gif]

Note that the total number of points used by Plot is bounded above by the product of the two values (PlotPoints - 1) and PlotDivision. Considering the default values used by Plot, this product would be (24)(20) = 480. So Mathematica  is using close to the upper bound of points in the default graph. For the second graph, the number of points used was

[Graphics:Images/appendix_gr_507.gif]
[Graphics:Images/appendix_gr_508.gif]

So the second graph, although vastly improved over the first, did not use that many more points than the first.

Next let's look at how Mathematica  used the sample points by plotting just the points for each graph.

[Graphics:Images/appendix_gr_509.gif]

[Graphics:Images/appendix_gr_510.gif]

[Graphics:Images/appendix_gr_511.gif]
[Graphics:Images/appendix_gr_512.gif]

[Graphics:Images/appendix_gr_513.gif]

These plots illustrate how Mathematica  knows to plot points close together where the graph has high curvature but is content to spread the points out where the curvature is close to zero.

Advanced Topic: Functions with Asymptotes

We will examine the way Mathematica  handles functions with a vertical asymptote using an example.

[Graphics:Images/appendix_gr_514.gif]

[Graphics:Images/appendix_gr_515.gif]

Note that Mathematica  appears to have drawn in the vertical asymptote. But that is not what really has happened. Remember that Mathematica  just samples values of the function at various points determined by the options PlotPoints, PlotDivision, and MaxBend, and then connects those points with straight lines.  What appears to be the asymptote is really just one of those line segments connecting a point on the left branch to a point on the right branch. The reason there is a break in the lines is that Mathematica  has truncated the graph at the top and bottom. To view all of the calculated lines, you can use the option PlotRange->All.

[Graphics:Images/appendix_gr_516.gif]

[Graphics:Images/appendix_gr_517.gif]

When you want to graph a function with a vertical asymptote,  it is usually better to split the graph along the asymptote. You can also add in the vertical asymptote separately, as well as any other asymptotes as follows.

[Graphics:Images/appendix_gr_518.gif]

[Graphics:Images/appendix_gr_519.gif]

Advanced Topic: Miscellaneous Options for Plot

Consider the following example.

[Graphics:Images/appendix_gr_520.gif]

[Graphics:Images/appendix_gr_521.gif]

Notice that the horizontal axis is not the x-axis, but the line y=1. Mathematica  uses its own discretion in placing the axes. If you want to override Mathematica 's decisions, you can use the PlotRange option of Plot.

[Graphics:Images/appendix_gr_522.gif]

[Graphics:Images/appendix_gr_523.gif]

The next example illustrates several of the Plot options.

[Graphics:Images/appendix_gr_524.gif]

[Graphics:Images/appendix_gr_525.gif]

A.5.3 Advanced Topic: Parametric Plots

Curves in the plane can also be described by pairs of parametric equations of the form
[Graphics:Images/appendix_gr_526.gif], [Graphics:Images/appendix_gr_527.gif]. We begin by examining different ways that circles can be parameterised.

Parameterisations of Circles

Let's consider two different ways to graph a circle. For definiteness, let's work with the circle centred at the origin having radius 2. An equation of the circle under consideration is given by

[Graphics:Images/appendix_gr_528.gif]

To use the built-in Mathematica  function Plot to graph the above equation, we need to solve it for [Graphics:Images/appendix_gr_529.gif]:

[Graphics:Images/appendix_gr_530.gif]
[Graphics:Images/appendix_gr_531.gif]

Notice the form that Mathematica  uses to present the two solutions: it is a list of two elements, each one of which is a list containing a rule. A rule is actually a special kind of list where the first element in this case is [Graphics:Images/appendix_gr_532.gif] and the second element is the function of [Graphics:Images/appendix_gr_533.gif]. Thus we can pick out the two desired functions and graph them together with the following:

[Graphics:Images/appendix_gr_534.gif]

[Graphics:Images/appendix_gr_535.gif]

Gee, that seemed like a lot of trouble just to graph a simple circle. Let's work on another approach -- a parametric approach. Recall that if you let t denote the angle made between the positive x-axis and the line from the origin to a point (x,y) on the circle, then each point on the circle is uniquely determined by the value of t, and hence, its coordinates are functions of t given by the set of equations

[Graphics:Images/appendix_gr_536.gif]
[Graphics:Images/appendix_gr_537.gif]

We can now use the built-in function ParametricPlot to graph the circle:

[Graphics:Images/appendix_gr_538.gif]

[Graphics:Images/appendix_gr_539.gif]

Well, that was a lot easier than our first method. In the parametric equations used above, the value of the parameter t has a geometric interpretation, namely, it measures the angle indicated below.

[Graphics:Images/appendix_gr_540.gif]

The example above illustrates one of the main methods of obtaining a parametric set of equations for a curve  -- using an angle which is intrinsic to the curve as the parameter.

As an example of this second method, again consider the circle of radius 2 centred at the origin.  Note that any line through the point (-2,0) of the form [Graphics:Images/appendix_gr_541.gif] intersects the circle in exactly one point other than (-2,0).  Thus, each point on the circle other than (-2,0) is uniquely determined by the slope [Graphics:Images/appendix_gr_542.gif] of such lines.  We can use Mathematica  to find the corresponding set of parametric equations as follows.

[Graphics:Images/appendix_gr_543.gif]
[Graphics:Images/appendix_gr_544.gif]

Let's graph the computed set of parametric equations and see what we get.

[Graphics:Images/appendix_gr_545.gif]

[Graphics:Images/appendix_gr_546.gif]

[Graphics:Images/appendix_gr_547.gif]

As expected, we get the circle of radius 2 centred at the origin -- most of it, that is.  Do you see why there is a gap in the circle?  What could be done to reduce the size of the gap?

Lissajous Figures

A Lissajous figure is a path traced out in the plane by a particle each of whose coordinates are under simple harmonic motion. Such trajectories are often encountered in physics. The first set of parametric equations of the circle in the previous subsection is an example of such motion. Let's try some other examples which generate Lissajous figures.

[Graphics:Images/appendix_gr_548.gif]

[Graphics:Images/appendix_gr_549.gif]

[Graphics:Images/appendix_gr_550.gif]

[Graphics:Images/appendix_gr_551.gif]

A.5.4 Advanced Topic: Polar Plots

In this section we will graph some curves in polar coordinates.  To begin with we need to recall the transformation equations from rectangular coordinates to polar coordinates.

[Graphics:Images/appendix_gr_552.gif]
[Graphics:Images/appendix_gr_553.gif]

So, to graph a polar equation like [Graphics:Images/appendix_gr_554.gif], all we need do is

[Graphics:Images/appendix_gr_555.gif]

[Graphics:Images/appendix_gr_556.gif]

Exercise: Now try to graph  r = 1 +  Cos[θ]

Exercise: Now try to graph a five petal rose.   

A.5.5 Animations

Mathematica  can perform animations of sequences of graphics. To generate such an animation, you first construct the list of graphics, often using a Do loop or similar construct.  Then you select the cell which contains the list of graphics by clicking the appropriate cell bracket.  Next, from the Cell pull down menu, you select Animate Selected Graphics.  At that point, you should begin to see an animation.  You can control various aspects of the animation by clicking on buttons on the lower left of the window.  Consult the Mathematica User's Guide for the Macintosh  for details.  

The following example illustrates various limacons -- those with loops, those without loops, and cardiods. As the parameter a varies, the limacon changes in a way which can be viewed by animating the generated graphics.  

[Graphics:Images/appendix_gr_557.gif]

[Graphics:Images/appendix_gr_558.gif]

As you might expect, Mathematica has a number of functions to ease the task of animation. The Add-on packige Graphics contains these functions. First, load the package.

[Graphics:Images/appendix_gr_559.gif]

For another animation, we can expand on the Lissajous figures introduced in the previous section. We will watch what happens as we shift the phase of the harmonic motion on the y-axis for a particular Lissajous figure. Animate the result of the following code and watch what happens.

[Graphics:Images/appendix_gr_560.gif]

[Graphics:Images/appendix_gr_561.gif]

It is not completely obvious how the interval for the parameter a was selected.  The idea was to use the smallest interval which brings the graph back to where it started.  

A.5.6 Implementation

Here is the Mathematica  code that was used to generate one of the circle graphics in the Parametric Plots section.

[Graphics:Images/appendix_gr_562.gif]

[Graphics:Images/appendix_gr_563.gif]

A.6 Exercises

A notebook containing solutions to the following exercises should be "turned in" as your lab report. Each student is responsible for writing a lab report independently. You will find an example notebook, report_example.nb, which contains an example of a report of the Example Exercise, and a template for the other excercises.

It is obligatory to do the Exercises 1 to 5. If you have time left you can also study the advanced topics and do the Advanced Exercises 1 to 3.

Example Exercise

Let [Graphics:Images/appendix_gr_564.gif].  Use Plot to graph this function on the interval [Graphics:Images/appendix_gr_565.gif]).  Then adjust the options of Plot to improve the graph as was done in the [Graphics:Images/appendix_gr_566.gif]. Determine the actual number of points used in the default plot and in your improved plot.

Exercise 1

Find a 10-digit number which is prime.

Exercise 2

Plot a graph of the function [Graphics:Images/appendix_gr_567.gif] 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

Let  [Graphics:Images/appendix_gr_568.gif]  and  [Graphics:Images/appendix_gr_569.gif] .
(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 4

Consider the function [Graphics:Images/appendix_gr_570.gif].
(a)  Using the symbolic capabilities of Mathematica , find simplified formulas for [Graphics:Images/appendix_gr_571.gif] and for[Graphics:Images/appendix_gr_572.gif]
(b) Find all real roots of [Graphics:Images/appendix_gr_573.gif] and of [Graphics:Images/appendix_gr_574.gif]. 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 [Graphics:Images/appendix_gr_575.gif], [Graphics:Images/appendix_gr_576.gif], and [Graphics:Images/appendix_gr_577.gif] 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.

Exercise 5

To gain practice and understanding of the Plot options PlotPoints, PlotDivision, and MaxBend, adjust these options so that the graph of [Graphics:Images/appendix_gr_578.gif] consists of exactly four straight line segments.

Advanced Exercise 1

Construct a graph of the function

[Graphics:Images/appendix_gr_579.gif]

as was done in the similar example. That is, split the graph along the vertical asymptotes. Also, graph the vertical asymptotes in a different color, and do the same for the skew asymptote.

Advanced Exercise 2

(a)  Graph the ellipse given by the equation

[Graphics:Images/appendix_gr_580.gif]

using ParametricPlot.  

(b)  Graph the hyperbola given by the equation

[Graphics:Images/appendix_gr_581.gif]

using ParametricPlot.

Advanced Exercise 3

This exercise concerns a famous curve called the "folium of Descartes."  The rectangular equation for this curve is

[Graphics:Images/appendix_gr_582.gif]

(a) To graph this equation, the first step might be to solve for y as a function of x.  Do this using the Solve function.  Observe that the result is a complete mess.  

(b) Rather than proceeding with the above train of thought, parameterise the curve using slopes of straight lines through the origin.  You can do this using the Solve function again, as was done in the Parameterizations of Circles subsection of the lab.  Note that the results tell you that such straight lines intersect the curve in at most one point other than the origin.

(c) Now try to graph the curve using the ParametricPlot function with an interval of [-10,10].

(d)  If all has gone correctly, you will have a plot which is not possibly correct.  It will contain curves and a straight line, and will not have the property that straight lines through the origin intersect the graph in only one point other than the origin -- a fact which is guaranteed by part (b) above.

(e)  Explain what has gone wrong, fix it, and give a correct graph of the folium of Descartes.


 
     
  Lectures | Notebooks | Packages

 
  Copyright © 2003 Wyższa Szkoła Zarządzania i Bankowości. Wszystkie prawa zastrzeżone
webmaster@wszib.edu.pl