Programming Paradigms via Mathematica

The Mathematica labs in this course are the collaborative creations of Rich Neidinger, John Swallow, and Todd Will and are organized into nine numbered chapters.  The first section of the first chapter follows.

Chapter I.  Introduction to Mathematica and to Programming

1. Arithmetic: Syntax, Data Types, Operators, and Expressions

Last revision: January 13 1998

In this section we explain how Mathematica can act as a graphing calculator, considering the evaluation and plotting of a variety of expressions.

Front End: Working, Saving, Printing

Congratulations!  You have successfully opened a Mathematica Notebook.

Before we may begin, we must cover a few basics of using Mathematica  The term front end refers to the user interface of a computer application; in our case, the "front end" of Mathematica is the layout of the windows, the menu bar, and the ways in which we input and output data under the operating system.  In this section we cover how to save and print your work.

Working in and Saving a Mathematica Notebook

You should always personalize a Mathematica document with which you are working so that it may be easily identified.  To do so, you should write your name (and the name of any of your partners) at the top of the document.  Right now, click in the tiny space above the "Programming Paradigms..." title above---so that you see a horizontal line---and begin typing your names.  Then scroll back to this cell, if necessary, and read on.

To save your work, you will need an appropriate place to save it.  You can save your work either to a disk or to a space on the network for which you have the appropriate privileges.  Since possibility always exists that the network connection will encounter difficulties, and since anyone is free to delete student files from the hard disk on this computer, please buy an formatted, double-sided, double-density disk, write your name on it, and always bring such a disk, with free space, to class.  You then retain, at all times, the opportunity to save your work.

The procedure to save your work is as follows.  Pull down the "File" menu to "Save As", indicate into which disk and folder you wish to save the file, and save the file under a name which will distinguish it from other notebooks.  For instance, John Doe might want to save the file as "L01Doe.nb", indicating John Doe's lesson one.  If you have a disk, try to save this notebook there.  (You can save two copies, one for each partner.)  Otherwise, go through the motions of saving but choose "Cancel" rather than typing a file name, and take notes on anything in this section that you type.  (You will always be able to get a fresh copy of this document from the network.)

Printing a Mathematica Notebook

To print a notebook, pull down "File" to "Print", choose "OK" or "Print" (right now choose "Cancel") and wait a few minutes for it to appear at a local printer.  To print only selected parts of a notebook, drag the cursor across the brackets on the right side of the screen.  Try this now and get several brackets marked with a dark bar.  After doing this, use "Print Selection" or, if this command is unavailable, pull down "File" to "Print" and you should see "Selection" marked in the box.

You will be asked to print your responses to the homework assigment associated with this lesson to demonstrate your facility with printing.

Cells and Evaluation

The primary structural principle of Mathematica notebooks is their division into cells.  Notice that this cell's innermost brackets (on the right-hand side of your screen) have a second bar on top.  This second bar indicates that Mathematica is prevented from trying to interpret its contents as instructions; the cell is simply a text cell.  Cells which we want Mathematica to look at and evaluate should not be text cells, but instead input cells. The first input cell below appears in blue—although it is possible to change the colors and background of all of the cells, both text and input.  First we will execute some input cells which are embeed in the notebook already, and then we will have you start making your own input cells.

To execute a cell, which means to ask Mathematica to evaluate it, use the mouse to place the cursor anywhere in the cell and click once.  You should then see a blinking cursor.  Then press the "Enter" key.  (Alternatively, hold down the shift key and press the "Return" key.)  Then Mathematica will execute the cell.

Let's see if Mathematica can do anything.  Execute the following cell:

4*5^2+13

You may have noticed that Mathematica took some time figuring this expression out.  If so, don't be worried.  The first time a Mathematica session executes an input cell, the computer has to launch a separate program, called the Mathematica Kernel, and starting up programs simply takes time.  Now that you have successfully executed a cell, read on through the notebook and execute every input cell that you see.

Arithmetic Operations

In this section we explain how Mathematica operates as a simple scientific calculator, evaluating expressions.  We will describe operators, which are usually symbols such as "+" which indicate to Mathematica that a certain sort of task, or operation (in this case, addition), must be performed.

The arithmetic operators have standard calculator form ("+", "-", "*", "/", and "^") and have standard mathematical precedence, meaning for instance that multiplication and division are executed before addition and subtraction.   Exponentiation has more precedence than multiplication and division, which have the same level of precedence, and these have more precedence than addition and subtraction, which have the same level of precedence.  The expression "4*5^2+13" should execute "5^2" first, followed by "4*(5^2)", finally followed by adding the "13".

4*5^2+13

Mathematica accepts some non-standard input forms for arithmetic.  For instance, the * may be omitted so that the multiplication is implied.  Of course, you still need a space so that Mathematica realizes that you do not intend the number 45.  Execute the following cells:

4 5^2+13

4 (5^2) + 13

Mathematica also allows variables, for which we can use a letter ("x") or a string of letters and numbers beginning with a letter ("my3rdvariable").  If you want to tell Mathematica to multiply a variable by a number, you don't need to use a space between them if the number comes first.

3x + 5x

However, "x3" and "x5" are interpreted as two different variables (as if the 3 and 5 were subscripts) and so the two are not combined.  While the cell above gives "8x" when executed, the cell below simply returns "x3+x5".

x3 + x5

Boolean Operations

Mathematica also has some functions which do not return a numeric value but instead return either true or false.  Since "True" and "False" are considered boolean values,  these functions are called boolean (for "boolean-valued") functions, and you know many of them:  less than, greater than, and so on.  Relational operators  compare two arithmetic expressions, and include equals ("==", two equals signs being necessary to ask if two expressions are equal), non-equal ("!="), greater (">"), less ("<"), greater-than-or-equal (">="), and less-than-or-equal ("<=").  Logical operators, on the other hand, manipulate true and false values, determining for instance whether both values are "True".  Mathematica's set of logical operators includes "and" ("&&"), which returns "True" if and only if both values are "True", and "or" ("||"), which returns "True" if either one or both values are "True".  Let's explore a few boolean operators:

\(3\  > \ 5	\)5  >  55  >=  55  ==  55  !=  5( 3  >  6 )  ||  ( 4  <  5 )

Note a few pitfalls:  the equality test has two equals signs, and the exclamation point means "not".  Note also that we may combine many operators into one expression, as in the following examples.

( 2  >  1 )  &&  ( 3  >  4 )

In this case the parenthesized expressions evaluate to "True" and "False", respectively, and then the "and" operator returns a "False", since the boolean values were not both "True".

\(\(\((\ 2\  > \ 1\ )\)\  || \ \((\ 3\  > \ 4\ )\)
\)\)

In this case the parenthesized expressions evaluate to "True" and "False", respectively, and then the "or" operator returns a "True", since at least one boolean value was "True".
What if Mathematica can't decide if one value is less than another?  In that case, it simply gives you your expression back ("unevaluated").  Try

Pi  <  22/7x  <  22/7

Operator Precedence

We have already seen the precedence of arithmetic operations. How does Mathematica decide in which order to perform other operations?  Mathematica has rules which determine the relative precedence of all of its operators, meaning that it knows which should precede the others in evaluating pieces of an expression.

For the operations we've seen, we explain the relative precedences.  First, arithmetic operations have higher precedence than relational and logical operations.

3 > 2 + 2

The expression above returns "False".  Note that since "+" has higher precedence, the 2 and 2 were added together to get 4, and then the expression "3>4" was tested.

Then, within the category of boolean operations, relational operations have higher precedence than logical operations.

5 > 4 && 1 > 2

Here, each of the "greater-than" expressions was evaluated first, so that the expression becomes
"True && False"; then the "and" takes over, and returns a "False".

Exact vs. Approximate Values

In Mathematica, there are two important sorts of values, exact and approximate. Exact values usually take more space to store inside the computer, and calculations with exact values require more time to insure an exact answer.  Approximate values usually take less space to store inside the computer, and calculations with approximations require less time, since an approximate answer is all that is required (or possible!).  In these two sorts of values we see an initial tradeoff in programming:  we may exchange computational time and storage space for precision.  In some cases, however, we might rather have exact answers and pay the price of time and space.

Exact values may either be (a) integers or fractions, in which case Mathematica keeps as many digits as necessary to express the value exactly, or (b) symbolic names for constants such as E, Pi, and Sqrt[2], from which Mathematica knows how to find as many digits as necessary in any computation.  Approximate values are most typically numeric expressions containing a decimal point.

If an expression contains only exact values, Mathematica will never approximate it and will instead leave the expression in a simple exact form.

2^100/6

If an expression contains at least one approximate value, Mathematica will approximate at least a portion of the expression.

2^100/6.

If we wish to convert an exact, or partially exact, expression to an approximate value, we use the function "N[]". (Note again that functions in Mathematica typically have a name followed by brackets, not parentheses.  Between the brackets we write the input values of the function, separated by commas, if there are two or more.)  The output of "N[]" is an approximate value, containing several digits in scientific notation.  The value is actually converted internally to a representation with 16 significant decimal digits.

2^100/(6. Pi)

N[2^100/(6. Pi)]

It is very important to realize the distinction between the approximation and the exact value.  Approximations, once used in an expression, force the expression to be approximated, so that it will then be precise only to a certain number of significant digits.   Once an approximation is presented (or computed) with some number of significant digits, no further significant digits can be coaxed from that resulting expression.  Only exact expressions retain their validity throughout any calculation.

We can illustrate the difference between exact and approximate values by using the "N[]" function.  Remember, the "N[]" function takes a value and tries to find an approximation with some desired number of digits (16 digits if only one expression is between the brackets after N, or, if there are two expressions separated by a comma between the brackets, then the number of digits specified by the second expression).   The "N[]" function should work best if the expression is exact, since we can find as many significant digits as we like, but a problem may occur if we ask "N[]" to extract more digits from an approximation which only has a certain number of significant digits.

Let's take a look at two cases.  First, we'll ask for the value of "2^100/(6*Pi)" to 50 significant digits.

N[2^100/(6 Pi),50]

This answer is exactly what we wanted, the value of "2^100/(6*Pi)" approximated to 50 significant digits.  Now we will ask for 16 digits of "2^100/(6*Pi)", and then ask Mathematica to find 50 significant digits of that number.

N[N[2^100/(6 Pi),16],50]

We can't draw water from a stone.

Before Proceeding:  Cell Grouping and Cell Styles

You will notice that certain cells below are multiply bracketed on the right side, and that some cell brackets have a peculiar arrow at the bottom.  Consecutive cells in Mathematica can be grouped together, and they can be "closed" and "opened", operations which, if nothing else, make a Mathematica notebook neater and more organized.  If you double-click on a rightmost bracket which does not have a lower arrow, you will open the group of cells bounded by that bracket, and if you double-click on a bracket without an arrow (and which bounds several cells inside), then you will close the group.  Try it out on this first group, headed by the section title "Exact vs. Approximate Values".  What you should notice is that the topmost cell stays around while the other ones close up.  The cells below are closed, and you will need to open them up to read them!

Each cell has a style, and you have seen several already.  Text cells have the double bar on the top of their bracket, and input cells are in bold Courier font.  There are many kinds of cell styles, including "Section" (the type of the "Exact vs. Approximate Values" cell above), "Output" (the usually red cells Mathematica returns to you after you evaluate a cell), as well as others like "Title", "Subtitle", and so on.  To find out which style a cell has, make sure your ruler is showing at the top of the screen (you can toggle it on and off under the Format menu), select a cell, and investigate its style at the left of the ruler.

Data Types

Data Types of Arithmetic Expressions

While the notions of exact and numeric values are most important in using Mathematica to calculate expressions, what is more important for programming purposes is to understand a finer distinction.  Mathematica, like many computer languages, has many data types, the most basic of which are Integer, Rational, and Real.  Any Mathematica expression must have some data type, as we will see below, and, further, any arithmetic value must have one of the three types Integer, Rational, or Real. To find out the type, simply put the value into the function "Head[]".

Head[5]

Head[7/3]

Head[0.78]

Mathematica uses different data types for different sorts of values.  For integers and fractions which should remain exact, Mathematica uses the data types Integer and Rational.  These data types are arbitrary-precision, meaning that Mathematica will keep as many digits of the integer or numerator and denominator as necessary to represent the value exactly.  There will be no decimal points in arbitrary-precision values.  On the other hand, the Real data type, sometimes termed floating-point, is indicated for the value by the presence of a decimal point, and Mathematica does not insist on keeping an exact representation of the value.  For instance, "1.5 * 10^100" is a Real value, since it contains a decimal point, and Mathematica will treat it as an approximate value. This distinction between exact and approximate value, as we've seen above, is important, since any expression containing at least one approximate value is in essence only a approximation and cannot ever be converted to an exact value.

Data Types of General Expressions

In fact, Mathematica's internal representation of expressions gives every piece of an expression a data type.  In Mathematica, this type is called a "head", and we can use the function "Head[]" to determine the head of any expression. For complicated expressions, the head typically describes the outermost operation in the expression.

Head[2+Sin[x]]

Head[Sin[x+7]]

Head[3 * (Tan[2] + 2)]

Data Types and Functions

When we study a function, an important piece of information to know is the data type(s) of the input value(s) and the data type of the output value.  Some functions take in a different data type from the one which they return.  One example is the function "N[]" discussed above; the function always returns a value of type Real, while you might put in a value of type Integer or Rational.  The function "N[]" is an example of a conversion function, which is a function that converts a value from one type to another.

Standard Scientific Functions

By now it should be apparent that all functions supplied by Mathematica use FirstLetterCap case and square brackets [].  What we usually write as "sin(x)", then, will now be "Sin[x]".  Some standard functions are "Sqrt[]", "Exp[]" (or "E^()"), "Log[]" (for the natural logarithm ln), "Log[b, ]" (for logarithm to the base b), "Sin[]", "Cos[]", "Tan[]", "ArcSin[]", "ArcCos[]", and "ArcTan[]".

Exp[-2] Sin[3 Pi/4]

N[Exp[-2] Sin[3 Pi/4]]

Plotting

Mathematica does a very good job of plotting many functions.  We introduce plotting in this section and in the next cover some of the details.

The following cell asks Mathematica to plot the function x^2 on the interval [0,1], with the syntax as follows.  The first expression between the brackets (called the first argument)  is the function.  The second expression, or argument, is a list (several items which are inside curly braces and are separated by commas).  The first element of this list is the variable which will be varied along the horizontal axis; the second element is the starting value of this value for the plot; and the last element is the ending value.

Plot[x^2,{x,0,1}]

Let's plot several functions, using the fact that braces can indicate several functions or data that all fall in a certain position in the argument list.  The following cell plots the functions x^2 and x together on the interval [0,3].

Plot[{x^2,x},{x,0,3}]

This shows that for x's between zero and one, x^2 is smaller than x.  A few more examples, with some extra options, which we consider in the next section, follow.

Plot[Exp[-Sqrt[x]] Sin[2^x], {x,0,2Pi}, PlotRange->All]

Plot[Exp[-Sqrt[x]] Sin[2^x], {x,0,2Pi}, PlotRange->All, PlotDivision->100]

Plot Options

In this section we present some of the plot options.

Plot[Exp[-Sqrt[x]] Sin[2^x], {x,0,2Pi}]

The graph above is acceptable, but we can make it more to our liking using plot options.  There are, in fact, a myriad of options, and while you are not expected to know them all, you will be expected to be able to use a reference or the Mathematica help function "?" to learn more about them.  Let's experiment with some options.

The plot above does not show the beginning of the graph.  To see it all, we add an option, "PlotRange->All", indicating that we want the vertical axis to extend far enough to include all of the "y-values" of the plotted points:

Plot[Exp[-Sqrt[x]] Sin[2^x], {x,0,2Pi}, PlotRange->All]

The plot looks jagged, however, around x=5.8, and we suspect that the reason is that Mathematica is connecting too few dots in the graph.  We add another option, "PlotDivision->100", to insist that Mathematica use 100 x-values to plot before connecting them with lines or curves.

Plot[Exp[-Sqrt[x]] Sin[2^x], {x,0,2Pi}, 
   PlotRange->All, PlotDivision->100
]

Whenever you are curious about a Mathematica command, preceding it by "?" and executing that command will instruct Mathematica to provide some information.  Try executing the following.  (You can also pull-down the menu "Help" and search.)

?PlotDivision

?PlotRange

The two options we have considered above pertain to the size of the graph and the number of points actually plotted.  Other options pertain to the "style" of the curves drawn.  Sometimes such options are very helpful, as for instance in the following plot of two functions, in which it is hard to distinguish between the two functions "x^E" and "E^x".

Plot[{x^E, E^x}, {x,0,4}]

We can distinguish different curves by dashing, color, or thickness, using the option "PlotStyle".  To use the option, place a list of (at least) two lists after the arrow ("->") following "PlotStyle", as follows.  The first list should contain features we wish to apply to the first function, and the second list should contain features which we wish to apply to the second function, and so forth.

Plot[{x^E, E^x}, {x,0,4},
  PlotStyle->{
    {Dashing[{.03}]},
    {}
  }
]

We can add color to a plot, though we must remember that printouts may not contain the colors that appear on the screen.  Before trying to use colors, execute the following "Needs" command.  This loads in a "package" which allows us to use the names of particular colors instead of being forced to specify them using the more cryptic "RGBColor" command.

Needs["Graphics`Colors`"];

Study the following cell, which also contains an option to frame the plot, to see how to add colors in the context of a "PlotStyle" option.

Plot[{x^E,E^x},{x,0,4},
  PlotStyle->{
   {Red, Dashing[{.02}]},
   {Blue}
  },
  Frame->True
]

(Note that if you want a bigger graph, you may click inside the graph, grab a corner, and drag it to the desired size.)

Many students find interesting the complete list of all of colors for which Mathematica knows names.  If the "Needs[ ]" command above has been executed, we need only evaluate the command "AllColors":

AllColors

To suggest other ways in which Mathematica may alter the final form of a plot, let's look at one more overwhelming list, namely all of the default  options for the "Plot[ ]" function.

Options[Plot]

You can explore the Plot command more fully by accessing the Help facility (in the menu at the top of the screen).  Try it!

Exercise

See the file "Hw01.nb".  Answer the questions there and hand your results in at the next class.