Tutorial 03
Symbols and Functions

Copyright © 2003 by Bill Titus, Carleton College,
Department of Physics and Astronomy, Northfield, MN  55057-4025
March 1, 2003

Part 1 - Getting Started

Step 1.  Start up Mathematica and open the notebook  Tutorial03.nb.  Remember, this notebook is located in the workshop folder.

Step 2.  OPTIONAL.  Since you're going to edit this notebook, you need to make a copy of this notebook and work with that copy.  To do so, select  File / SaveAs  from the Mathematica menu and save the notebook in the workshop folder under the name  myTutorial03.nb.

Comment 2

1.  Remember, Mathematica occasionally malfunctions so it's best to save your results frequently if you want a record of the notebook.

Part 2 - The Problem of Interest

In this notebook, you'll solve the first part of the following problem, which is taken from Mathematics:  A Simple Tool for Geologists by David Waltham (Chapman & Hall, London, 1994, page 38).

The rate of accumulation,  p,  of carbonate sediments on a reef is given approximately by   p = (Subscript[p, 0])exp(-z/(Subscript[z, 0])),  where  (Subscript[p, 0]) and  (Subscript[z, 0])  are constants and  z  is the depth below sea level.

(i)     Calculate  p  at depths of  0.0,  2.0,  4.0,  ... , 20.0 m  if  (Subscript[p, 0]) = 3.0 m (ky^(-1)) and  (Subscript[z, 0])= 20.0 m.
(ii)    Sketch the results.
(iii)   Give an interpretation for the constants  (Subscript[p, 0])  and  (Subscript[z, 0]).

Part 3 - Mathematica Constants and Help

Topics and Skills

1.  Mathematica help using  ?
2.  The Help Browser (HB)

Step 1.  In doing this calculation, you're going to need to the value of the exponential constant  E.   Type  ?E   in the cell below and see what happens.

Comment 1

1.  The symbol  ?  is your friend.  It's an extremely useful Mathematica command and gives help on Mathematica and user-defined symbols and functions.

Step 2.  See what happens if you click on   More...  in the output cell associated with  ?E.

Comment 2

1.  When you clicked on  More... , you open up Mathematica's Help Browser (HB), which contains all the information from two documentation books:  The Mathematica Book (Fourth edition, Version 4) by Stephen Wolfram and Mathematica 4: Standard Add-On Packages by Wolfram Research.  Both books are available from Wolfram Research (http://wri.com)  and are usually included when you purchase the software.

Step 3.  While you're in the  HB  for  ?E,  open up  Further Examples  by clicking on the nearby triangle.

Step 4.  Now try clicking on any of the blue underlined text and see what happens.

Comment 4

1.   This operation will take you to pages in related documentation.
2.  You can return to your original help page by using the backward arrow in the upper left hand corner of the panel.

Step 5.  You can also get to the  HB  by selecting  Help / Help Browser ...  from the Mathematica menu bar and using the search capabilities of the panel that comes up.  Try this out by getting help on the symbol   E.

Step 6.  As practice, get help on the three Mathematica constants:  Pi,  Degree,  and   I.

Comment 6

1.   Mathematica uses letters (symbols) not only to define constants, but functions and other constructs within Mathematica.  Just remember that any Mathematica defined quantity will start with a capital letter.

Part 4 - User-Defined Symbols

Topics and Skills

1.  Using symbols for calculations
2.  Immediate assignment with  Set[]
3.  The "context" for a symbol
4.  Multiple inputs in a single cell
5.  A semicolon to suppress output

Step 1.  Now you're going to do the sediment calculations using our own symbols.  Type in the following code in a new cell below, pressing the  (enter)  key each time you're done with a single line.

p0 = 3
z0 = 20
z = 2.0
p = p0*E^(-z/z0)

Comment 1

1.  Note that all the inputs and outputs are in separate cells.
2.  Symbols are used to stand for quantities, including numbers, equations, expressions, and even collections of other symbols.  They're used to make your calculations clear and flexible, and to help you organize your results.  
3.  Remember, since Mathematica starts its symbols with capital letters, it's best to start yours with lowercase letters.  That way you avoid any possibility of conflicting with Mathematica defined quantities.
4.  The equal sign (also called  Set[]) is an immediate assignment.  For example, as soon as you enter the expressions for  p0  and  z0 on the right hand side of the equal sign,  the symbols  p0  and  z0  are assigned those values.
5.  I don't use white spaces in equations.  Mathematica seems to do a good job of formatting equations so that they're readable without white spaces present.

Step 2.  Type  po,  z0,  z,  and  p  on separate lines, each followed by  (enter),  to confirm that the symbols have the values you entered.

Step 3.  You can also confirm the values of your symbols using the Mathematica help command  ?.  Type  ?p  in the cell below and see what happens.

Comment 3

1.  The word  Global` signifies the "context" where your symbol is stored.  For example, the full name of the symbol  p,  as far a Mathematica is concerned, is   Global`p.  Symbols may be stored in different contexts; the default context for user defined symbols is  Global`.  Symbols Mathematica defines are stored in the context  System`.   I find it useful to think of a context as a folder where something is stored.

Step 4.  Repeat Step 2, but this time type in the symbols in the same cell, but with the symbols on different lines.  Use the (return) key to produce line breaks.

Comment 4

1.  Typing all of your symbols in one cell allows you to evaluate all the symbols by only pressing the (enter) key once.
2.  Note, however, that the output still occurs in four separate cells.

Step 5.  In your calculation, there's no doubt to the numerical values of  p0,  z0,  and  z  and what you want to know is the numerical results for  p.  You can suppress the output from a line by putting a semicolon at the end of the line.  Activate the code below and observe that the only output that now appears is that associated with the symbol   p.

p0 = 3;
z0 = 20;
z = 2.0;
p = p0*E^(-z/z0)

Comment 5

1.  You now have a very compact way of doing your calculation.  All you have to do is go back to your single cell, change the value for  z,  press the (enter) key, and record the numerical value that pops out.  However, you can do better if you use Mathematica's capability for creating functions.  That will be the focus of the next two sections.

Part 5 - Mathematica Defined Functions

Topics and Skills

1.  Notation for a function
2.  Some Mathematica functions:  N[],  ScientificForm[],  Plus[],  Power[],  Times[],  Divide[],  FullForm[],  Exp[],  Sin[],  Cos[],  Tan[],  and  Clear[].

Step 1.  In Mathematica, a function consists of a symbol, followed by a set of square brackets, and arguments that you put inside the square brackets.  For example, in  Tutorial01.nb,  you used the Mathematica function  N[]  to find the numerical value of rational numbers.   In a single cell below, type in  N[2/3],  N[2/3,50],  N[E,50],  and   N[π,50] and then press the (enter) key.

Comment 1

1.  There must be over a thousand built-in Mathematica functions, many of which you'll never use.
2.  In "standard" notation, a function comes with a "head", which is the symbol naming the function, and square brackets, which are used to contain the argument(s) of the function; multiple arguments are separated by commas.  Mathematica defined functions always start with capital letters; if they contain more than one word, each word is capitalized; abbreviations are usually not used unless there are standard ones available.

Step 2.  Use the Mathematica help command  ?  to find out information about the Mathematica function  N[].  Don't include the square brackets when you ask for Mathematica help,  i.e.,  just type  ?N .

Step 3.  Here are some Mathematica functions that you have already used:  Plus[],  Power[],  Times[],  Divide[],  and ScientificForm[].  Get Mathematica help on each of the functions and be sure you understand what they do.

Step 4.  To reinforce what the four functions  Plus[],  Power[],  Times[], and  Divide[]  do, activate the cell below.

Plus[a, b]
Power[c, α]
Times[a, b, c]
Divide[a, b]

Comment 4

1.  Almost everything in Mathematica is coded in terms of functions, which Mathematica calls "expressions".  For example, when you type   a + b,   Mathematica really stores the information as the function  Plus[a, b].  As a matter of fact, Mathematica would be quite happy if everyone in the world wrote  a + b   as  Plus[a, b].  This notation makes absolute sense since addition is really a function that takes two numbers and gives you a particular one back in exchange.

Step 5.  If you really want to know how Mathematica stores the code you type, you can use the Mathematica function  FullForm[].  Get help on this function and then apply the function to the equation  a - (b^c) .

Comment 5

1.  You'll find  FullForm[]  useful if you need to find out a particular part of a result or equation.  You'll see an example of this need in a later tutorial notebook.

Step 6.  Get Mathematica help of the functions  Exp[],  Sin[],  Cos[],  Tan[],  and  Clear[]  and be sure you understand what these functions do.

Step 7.  To see an example of   Clear[] in action, activate the cell below.

p
Clear[p]
p

Step 8.  Mathematica has several ways to apply a function to one or more variables.  The way you have been applying functions is the most commonly used one.  However, sometimes it useful to apply a function after the fact, so to speak (this is, the postfix notation you've seen in previous tutorials).  Look over the code below, activate the cell, and see if you understand what's happening.

x = π/3;
y = 3*Sin[x]*Exp[Cos[x]]
y // N
y // N[#, 50] &
y // Tan
y // Tan // N

Comment 8

1.  The application of a function after the fact is call the postfix notation.  It consists of  //   followed by the function you want to apply.   If the function has only a single argument, you just need to include the head of the function.  However, if the function has more than one argument, you must use #  as the variable on which you are applying the function, and then terminate the function with the symbol  &.
2.  One advantage of postfix notation is when you want to do something quickly to a result of a rather lengthy calculation you have already completed.  In this case, all you have to do is tack the function you want to apply to the end of your calculation.  You'll see applications of the postfix notation in some of the later tutorial notebooks.

Part 6 - User-Defined Functions

Topics and Skills

1.  User-defined functions using  Set[]  and simple patterns
2.  User-defined functions using  DelayedSet[]  and simple patterns
3.  The Mathematica  Table[] command
4.  A little bit on lists

Step 1.  Reread the problem you want to solve.

The rate of accumulation,  p,  of carbonate sediments on a reef is given approximately by   p = (Subscript[p, 0])exp(-z/(Subscript[z, 0])),  where  (Subscript[p, 0]) and  (Subscript[z, 0])  are constants and  z  is the depth below sea level.

(i)     Calculate  p  at depths of  0.0,  2.0,  4.0,  ... , 20.0 m  if  (Subscript[p, 0]) = 3.0 m (ky^(-1)) and  (Subscript[z, 0])= 20.0 m.
(ii)    Sketch the results.
(iii)   Give an interpretation for the constants  (Subscript[p, 0])  and  (Subscript[z, 0]).

Step 2.  Activate the code below that finds the numerical solution to the problem using symbols.

p0 = 3;
z0 = 20;
z = 2.0;
p = p0*E^(-z/z0)

Step 3.  You're now going to define your own function  p[z]  such that given a value of   z,   your function will tell you the value of   p .  To do so, look over the code below and enter the results.  Then try out your function with the value  z = 4.0  and  z = s,  where  s  is an arbitrary symbol. i.e,  type in  p[4.0]  and  p[s]  and enter the results.

Clear[p0, z0, p, z]
p0 = 3.0;
z0 = 2.0;
p[z_] = p0*Exp[-z/z0]

Comment 3

1.  Note that by defining the function  p[z],  you can calculate  p[z]  anywhere in your notebook.  You don't have to go back to the original cell that defined the function, as you would with the original symbol version of the calculation in Step 2.
2.  The  Clear[]  function makes sure all your variables are undefined at the time of your definition.  Many times you can get away without having to include  Clear[]  in your code, but sometimes you can get into problems.  Before any function definition, I always include a  Clear[]  with arguments corresponding to all the variables I'm plan to use in the function definition as well as the name of the function.  It's better to be safe than sorry, and it does help you focus on the variables you need in defining your function.
3.  The underscore (also called a "blank") implies that  z  is the argument of the function whose name is  p .  Anything put into this slot will replace the corresponding symbol on the right hand side of the function definition.  The combination of a symbol and an underscore, like   z_,  is called a simple pattern.
4.  Be careful with underscores.  In a function definition, underscores must appear on the left hand side of the assignment statement and only on that side.  A common error is to forget to put in the underscore.  Mathematica will let you get away with this since the expression without an underscore is a valid construct, although it only works for the explicit symbol you put in the square brackets on the left hand side of the defining equation.
5.  Note the way in which Mathematica outputs the symbol for  E.

Step 4.  To see the problem that's created by not putting an underscore in the argument on the left hand side of the defining equation for  p[z],  activate the code below, and then find   pp[4.0],  pp[s],  and  pp[z].

Clear[p0, z0, pp, z]
p0 = 3.0;
z0 = 2.0;
pp[z] = p0*Exp[-z/z0]

Comment 4

1.  Without the underscore,  pp[]  is only defined for the symbol  z.  On the other hand,  p[] is defined for anything you want to put in there as an argument,  i.e.,  p[CarletonGeology]  is a perfectly well-defined quantity.

Step 5.  Get Mathematica help on your two functions  p[]  and  pp[].

Comment 5

1.  If your function isn't doing what you believe it should, the first thing you might try is to get help on the function and see what Mathematica has stored for your function.  Many times you'll be surprised and thus be able to detect your error.

Step 6.  When defining a function, one of the things you must do is decide which of your quantities are constants and which are variables.  For example, in your definition of  p[],  you choose  p0  and  z0  to be constants  and  z  to be the variable of interest.  But suppose you want to vary  p0  and  z0  as well.  You can easily do that by defining a function  pNew[]  with three variables.   Look at the code below, activate the cell, and apply the results to  (Subscript[p, 0]) = 2.0,  (Subscript[z, 0]) = 4.0,  and  z = 2.5.

Clear[pNew, p0, z0, z]
pNew[p0_, z0_, z_] = p0*Exp[-z/z0]

Comment 6

1.  If you don't want to output the general form of your equation when you define it, put a semicolon after the definition on the right hand side of the equation.  The semicolon will suppress output.

Step 7.  There's one more symbol that is used to define functions and that is the symbol := , which is equivalent to the function  SetDelayed[].  Activate the code below and see if you can tell the difference between  =   and  := .

Clear[pD, p0, x0, z]
p0 = 3.0;
z0 = 2.0;
pD[z_] := p0*Exp[-z/z0]
?pD

Comment 7

1.  Note that to two lines of code

	p0 = 3.0;
	z0 = 2.0;
	
are not needed in using  SetDelayed[],  and, as a matter of fact, only confuse the issue.
2.  Basically,  SetDelayed[] doesn't evaluate any of the symbols used in its definition until it's called.  On the other hand,  Set[]  evaluates any symbol that has a value, except for the variables listed in its argument.
3.  I usually use  SetDelayed[]  in defining functions, unless there's a real good reason to use  Set[].  The distinction between these two function will become clearer as you get more practice using Mathematica.
4.  Even though there is no semicolon at the end of the line defining  pD[z],  Mathematica didn't echo the equation back to the screen as it would have for a  Set[]  definition.  This is just the nature of the beast.

Step 8.  Now that you have a function   p[z] defined, how do you evaluate it for a number of values for  z  other than typing in each value separately?   To do so, you're going to use the Mathematica function   Table[].   Mathematica help is a bit confusing with respect to this function, so first activate the code below and see if you can determine what   Table[]  does.

Table[2*i + 1, {i, 0, 10}]
Table[2*i + 1, {i, 0, 10, 2}]

Comment 8

1.  Anytime you see curly brackets used in Mathematica, it's with respect to lists of things.  In the  Table[]  example above, the output is in terms of a list of values calculated via the equation given as the first argument of  Table[].  The second argument of  Table[]  is a list of three quantities in one case and four quantities in the other:  the variable i,  the starting value for  i,  the final value for i,  and, if present, the increment between values for  i.

Step 9.  Get Mathematica help on   Table[] and see if the explanation makes sense.

Step 10 - Apply the  Table[]  command to your function  p[z]  to generate the values for  p  corresponding to  z  going from  0.0  to  20.0  in steps of  2.0.

Part 7 - Save Your Notebook (OPTIONAL)

Step 1.  Delete all your output cell.   Remember, to do this task, go to the menu bar and activate  Kernel / Delete All Output Cell.  A panel will come up asking whether you really want to do this or not.  Press  OK  and the output cell disappear.

Step 2.  Save the notebook one last time, and quit Mathematica.