Laboratory 1 
Basics of Mathematica

1.1 Notebooks

A standard Mathematica file is called a notebook and has extension .nb. For example, the present file is named Laboratory 00.nb. To create a new notebook, select File -> New -> Notebook from the main menu or press  Ctrl +N. That will result in a new window filled with white space and named Untitled-1, Untitled-2, or similar.

Exercise 0.A. Create a new notebook and save it with the name LabReport.nb.

You may notice that the current window has a little toolbar on top but that toolbar is missing in your newly created notebook. You can activate or deactivate the toolbar by sellecting Window -> Show Toolbar from the main menu.

Exercise 0.B. Activate the toolbar of the notebook LabReport.nb that you created and save the notebook afterwards.

1.2 Cells

Notebooks consist of one or more cells. For example, the present paragraph is contained in a text cell, and the section name above ("0.2 Cells") is contained in a section cell. Each cell represents a logical unit of the notebook and is shown by a blue square bracket on the right side of the screen. There are several different types of cells, but the three main types are: input cells, output cells, and text cells. In addition to these, there are types of cells that provide special formatting: title cells, subtitle cells, section cells, etc.

1.2.1  Selecting and Editing Cells

To select an existing cell, click on its cell bracket. A selected cell is indicated by a thick black bracket. To select more than one consecutive cell, click on one cell bracket and then drag over the others or click on the desired cells while pressing the Ctrl key down. To select cells that are not next to each other, click on the first one then, while holding the Ctrl key down, point and click on the next one and so on. This is particularly useful in printing a selection of cells. One can also copy and paste selected cells. 

To edit the content of a cell, simply click on the desired location and start editing. One can also change an entire cell by selecting it and choosing a different style type from the pull-down menu in the toolbar.

Exercise 1.  (a) Select the title cell of this notebook and copy it to the notebook LabReport.nb, which you created in Exercise 0. 
(b) Use the toolbar to change the style of the title of LabReport.nb from Title to Subtitle.

1.2.2  Creating a New Cell

If you position the mouse between two existing cells or after the last cell and then click, a horizontal line (called the cell insertion point or line) will be shown across the screen. This indicates where the next new cell will be inserted. Now, if you begin to type, Mathematica will create a new cell containing the text that you type. If you type several lines (using the ⌤ key to begin new lines), the cell bracket will grow to enclose everything you type. Note that, by default, every new cell you type in is created as an input cell. That means that Mathematica treats the symbols inside that cell as Mathematica code and may try to execute it. That is not always desirable, so you must always convert the style of cells you consider text from Input to Text. For example, a cell containing your name should have type Text, Subtitle or Subsubtitle, not Input.

Exercise 2. (a) In LabReport.nb, create a new cell after the title cell that contains your name and today's date.
(b) Change the style of the new cell to Subsubtitle and center the text in it. (Use the toolbar to format the whole cell).
(c) At this point,  LabReport.nb should be a good template for future lab reports. Save it and then save it again under the name Lab00Report.nb.

1.2.3 Executing Cells

To execute a cell (to get an answer to an arithmetic operation, for example), press the ⇧ and ⌤ keys simultaneously (or press the ⌤ key on the numeric key pad) after placing the cursor anywhere within the cell. As soon as a cell is executed, it will be labelled with In[1] for the first cell. The result will be shown in a new cell labelled Out[1]. The next cell executed will be labelled In[2] regardless of its actual location relative to the first cell. Mathematica pays attention only to the order in which the cell is executed rather than to its relative position with respect to other cells. To see this in action, try to execute the following cell.

2+2

Note that Mathematica will execute only input cells.

Sometimes, one wants to execute more than one cell. That can be done by cellecting the desired cells and then pressing  ⇧+⌤. One can also execute the entire notebook by selecting Evaluation -> Evaluate Notebook from the main menu. This will make Mathematica run through the entire notebook and execute all input cells in the order of appearance. Note that if there is text contained in an input cell, Mathematica will try to execute that text.

Exercise 3. In Lab00Report.nb, create a new input cell containing the following text:

	Today is 12/13/2010.

1.3 Arithmetic Operations and Numerical Values

Mathematica supports the basic arithmetic operations. The following symbols are used:

	+	indicates addition
	-	indicates subtraction
	*	or a space (sometimes a space is unnecessary) indicate multiplication
	/	indicates division
	^	indicates exponentiation  
	

Try the following (one at a time!):

2+2*3

2+2 3

5^3

2/3-1/6

Notice that Mathematica returns the sum of two rational numbers as a rational number. That is because by default, Mathematica uses exact arithmetic. This means that a rational number, such as (1/2), will normally be displayed as a fraction and not as the decimal 0.5, which is considered an approximation having a limited precision. If we want the numerical value of a fraction, we can use the built-in command N[]. In general, the command

	N[..., n]

returns the numerical value of the expression in place of the ..., with n correct decimal digits. When the value of n is missing (as in the above example), the default precision is used. To get the numeric value of (7/94), try the following:

N[7/94]
N[7/94,30]

An alternative way to get the numeric value of an expression is to add a left apostrophe (`) after it: for example, 7/94` has the same effect as N[7/94]. 

It is important to remember that Mathematica performs arithmetic computations in the usual mathematical order: exponentiations are performed first; then multiplications and divisions, from left to right; finally, additions and subtractions, also from left to right. When this natural order is to be changed, we use parentheses. For example, the input

	2^3 - 1/3*4 + 13
	
represents the expression (2^3)-(1/3)*4+13 = 8-(4/3)+13= 19(2/3). On the other hand, the expression

(((2^3)-1)/((3^4)+13))=(7/94)

is represented by the input
	(2^3 - 1)/(3*4 + 13).

Exercise 4 (KenKen). Using parentheses and the five arithmetic operations (+,-,*,/,^), produce the given answers from the given numbers. For example, the answer 0.0005 can be obtained from the numbers 1, 1 and 2000 as 1./1/2000. (Note the decimal point after the first 1: without it the result would be (1/2000).)
(a) Use 10 and 3 to get 1000.		(b) Use 2, 5 and 3 to get 1000.
(c) Use 5, 1 and 3 to get (4/3). 		(d) Use 5, 1 and 3 to get (5/3).
(e) Use 5, 1 and 3 to get 2.		(f) Use 5, 1 and 3 to get -2.5.
(g) Use 5, 1 and 3 to get 2.5.

1.4 Elementary Built-in Functions and Constants

Some of Mathematica's built-in constants are: Pi, E, and I. (Mathematica is case sensitive!)  All built-in constants and functions in Mathematica begin with an upper-case letter. Furthermore, function arguments in Mathematica are enclosed in square brackets ([]), as opposed to the parentheses used in usual mathematical notation. Hence, the input Sqrt[16] gives the output 4, whereas, sqrt[16], Sqrt(16), or sqrt(16) do not work. Here are some of the elementary built-in functions that you will be using often:

  Function                              			Description                       	 	Usual Notation

Sin[x],Cos[x],Tan[x],Sec[x]	Trig functions		    		sin x, cos x, tan x, sec x
ArcSin[x],ArcCos[x],...		Inverse trig functions			(sin^(-1))x, (cos^(-1))x,...
Sqrt[x]					Square-rooting function		(Sqrt[x])
Abs[x]					Absolute-value function		|x|
Log[x]					Natural logarithmic function		ln x
Log[b,x]					Logarithmic function with base b	(Subscript[log, b]) x
N[x,n]					Approximate numerical value of x
Exp[x]					Natural exponential function		(e^x)
n!						Factorial of n				n!
 
Mathematica gives exact results whenever possible. So, typing Pi as input will return π. A numerical approximation to Pi can be found using the function N[] as follows.

N[Pi]

Note that, to improve readability, only six digits are displayed by default. More digits may be displayed using the function N[], as in the next example which gives the decimal expansion of π to 20 significant digits.

N[Pi,20]

Try the following:

Sin[Pi/2]

Log[10,1000]

Log[10,200]

N[Log[10,200]]

5!

As we mentioned earlier, Mathematica considers decimals, such as 0.5, approximate numbers. Therefore, most numerical calculations using such decimals are limited in precision. For example, compare the outputs of the following two calculations:

N[E^(1/2),50]
N[E^0.5,50]

In the first calculation, we ask Mathematica to evaluate (e^(1/2))=(Sqrt[e]), which is an exact number having an infinite precision. The second calculation, on the other hand, is limited in precision by the presence of the exponent 0.5, which Mathematica treats differently from 1/2. For this reason, it is preferred to represent decimals by fractions in numerical calculations.

Exercise 5. Compute the following. Give approximate values to 10 decimal places when appropriate.
(a) 51!			(b) 27! / 25!		(c) (Subscript[log, 10])235		(d) ln 71          
(e) (Subscript[log, 2])1024		(f) sin (π/10)		(g) (sin^(-1))0.25		(h) (Sqrt[7])	    
(i) cos 1.6		(j) ln (e^3)			(k) |-2.3|		(l) tan (π/6)

1.5 Defining Your Own Functions

To define a function:

	1. we use an underscore character _ after its argument name on the left-hand side of the defining equation; 
	2. we enclose the argument between square brackets;     
	3. we use :=  (this is called the delayed assignment operator) to separate the name and arguments of the function from its definition. 

This is called in Mathematica a delayed assignment. The left-hand side specifies the name and the argument(s) of the function. The right-hand side describes what the function does. For example, execute the following:

f[x_]:=x^2

If you ask Mathematica for f[5], it will return 25.

f[5]

A function in more than one variable is defined in a similar way. For example,

g[x_,y_]:=2 x^2 + Sin[y]

g[3,Pi/2]

Note that Mathematica becomes aware of the definition of a user-defined function not when the one has typed in the definition of the function, but only after the cell containing that definition has been executed. A common mistake is to type the definition of the function one wants to study and then to move on to study that function without executing the definition first. If the function has not been previously defined, Mathematica is likely to simply repeat any input that uses the undefined function. For example, try the following:

someNewFunction[5]

The situation is even worse if one is trying to redefine an already defined function but does not execute the new definition. For example, suppose that we type without executing it the following definition:

f[x_] := Sin[x]

If we now try to evaluate f(π), Mathematica will simply use the last known definition, which in this case is f(x)=(x^2) and results in an incorrect output:

f[Pi]

A remark about the command Clear

Mathematica will remember the values or rules that we assign to symbols even if we erase these definitions (or even close the notebook in which they were introduced). In order to force Mathematica to forget these assignments and values and be able to use the same symbol in a new context, we have to clear the old definitions first and start afresh. This is done through the use of the built-in function Clear as shown below.

Clear[f,x]

A remark about how evaluation works (Optional)

Consider the function

f[x_]:=x^2

This function defines a rule for f with an arbitrary argument. If we enter the following definition

f[x]=Sin[3]

this would be a definition of the expression f[x]. Now we have two rules for f[x]. When more than one rule applies, the more specific rules are tried before the more general ones. Thus, the rule for f[x] is tried before the rule for f[]. Hence,

f[x]

But, since we do not have a specific rule for f[y] or f[3], the general rule will be used.

f[y]
f[3]

The above discussion shows what happens if we do not use the colon and the underscore when defining a function. Let's see what happens if we used the underscore and not the colon. Consider the function h(x)=(x^3) which we will define below without the colon.

Clear[h,x]
h[x_]=x^3

If we ask now for h(t) or h(4), we will get the expected answers.

h[t]
h[4]

However, if x was assigned a specific value, say 2, at some point before h was defined, then the execution of h[x_]=x^3 would yield 8 as expected and this value will not change even if we later change the argument of the function h. This should be apparent from the following examples.

Clear[h,x]
x=2
h[x_]=x^3
h[x]
h[t]
h[4]

Exercise 6. Define the functions f(x)=sin x and g(x)=(x^2)-3. Then find the following numbers and functions, giving numerical approximations when appropriate.
(a) f(π/6)			(b) g(t)			(c) f( g(2) )	
(d) g( f(x) )			(e) g(g(t))

1.6 Lists

Many of Mathematica's more sophisticated commands have inputs and outputs in the form of lists. A list is a collection of expressions (numbers, variables, functions, other lists, etc.) separated by commas and enclosed in a pair of curly braces. For example, {x,0,2} is a list of three elements: the variable x and the numbers 0 and 2. Here is another example:

L={1,3,5,7,9,11}

This defines a list L whose elements are the odd integers 1, 3, ..., 11. When a list has been given a name, we can use that name followed by a number in double brackets ([[ ]]) to access a specific element of the list. For example, the fourth element of the list L above can be obtained by L[[4]]

L[[4]]

Thus, we have now encountered four different types of brackets in Mathematica, each with its own dedicated use. These types are:

	()			Round parentheses are used to indicate the order of operation. Do not use braces or brackets instead.
	[]			Square brackets are used for the argument of a function. Do not use round parentheses instead.
	{}			Curly brackets (braces) represent lists. 
 	[[]]		Double square brackets refer to a particular element of a list.

1.7 Plotting a Function of One Variable

1.7.1 Basic Plots

To graph a function (or an expression) of one variable, use the Plot command. The Plot command takes at least two arguments, a function (or an expression), and a range. The range is a list of three elements: the variable in the expression, for example  x, a minimum value for x, and a maximum value for x.

Try the following:

Plot[Sin[x],{x,0,2*Pi}]

One can also graph a previously defined function by using its name as the first argument of the Plot command as shown in the following example.

Clear[f,x];
f[x_]:=Cos[E^x]

Plot[f[x],{x,0,3}]

Exercise 7. 
(a) Plot the graph of the polynomial(x^2)+3in the interval[-2, 2].			
(b) Define g(t)=tan (t/2) and graph it in the interval [-3, 3].			
(c) Defineh(x) = sin((x^2)) and graph it in the interval [-2,3].

1.7.2 Graphics Options

An option is a rule of the form OptionName->OptionValue, where OptionName is the name of the option and OptionValue is the value that it is assigned. If an option is not supplied explicitly, the default value is used. The following command will display all the possible plotting options in Mathematica together with their default settings.

Options[Plot]

1. We can simulate graphing paper using the following option:

Plot[Sin[x],{x,-2 Pi,2 Pi},GridLines->Automatic]

2. With the function RGBColor, we can specify a color. RGBColor takes three arguments: the amount of red, the amount of green, and the amount of blue. These arguments must be numbers between 0 and 1. They don't need add up to 1. There are also several predefined colors that can be assigned to PlotStyle; these include: Red, Green, Blue, Yellow, Cyan, Magenta, Orange, Purple, LightBlue, Darker[Red], and other common colors. Try the following:

Plot[Sin[x],{x,-4,4},PlotStyle->{Thick,RGBColor[0.8,0.2,0.2]}]
Plot[Sin[x],{x,-4,4},PlotStyle->{Thick, Darker[LightGreen]}]

3. We can specify the range of values (on the y-axis) for which the plot should be displayed using the option PlotRange. The default setting displays the range where Mathematica thinks the function is "interesting". For example the following command will not display the entire graph of sin x/x.

Plot[Sin[x]/x,{x,-20,20}]

Setting the PlotRange to All will show all the values that Mathematica used in the plot.

Plot[Sin[x]/x,{x,-20,20},PlotRange->All]

The following command will produce a plot whose y-axis goes from 0 to 1.

Plot[Sin[x]/x,{x,0,4Pi},PlotRange->{0,1}]

1.7.3 Superimposing Several Graphs

One can superimpose the graphs of several functions by supplying the functions as a list in the first argument of the Plot command. The following command will plot sin x and x-(x^3)/6 +(x^5)/120.

Plot[{Sin[x],x-x^3/6+x^5/120},{x,-5,5}]

One can use the PlotStyle option to get more distiguishable curves as seen in the following example. Notice that the argument of PlotStyle is a list of two lists: the first list is the list of plotting options applied to the graph of sin x and the second list is the list of plotting options applied to the graph of x-(x^3)/6 +(x^5)/120.

Plot[{Sin[x],x-x^3/6+x^5/120},{x,-5,5},PlotStyle->{{Thick,RGBColor[1,0,0]},{Blue}}]

1.8 Getting Help

To obtain help on any built-in command Command, enter ?Command. For example, to learn how to use the built-in function Plot, enter ?Plot.

?Plot

More extensive description may be obtained by using "??" instead of "?". Wild cards (*) can also be used. So, to get a list of all built-in objects/functions that start with Exp, we enter ?Exp*.

?Exp*

The Function Navigator in the Help menu also contains all built-in functions and commands.

1.9 Dynamic Evaluation

A major improvement in Mathematica 6 compared to previous versions is the ability to handle dynamically updated variables. The basic command to access Mathematica's dynamic features is called Manipulate. It takes two or more inputs: the first input is the expression that we want to update dynamically and the subsequent inputs are lists indicating ranges of parameters that appear in the expression. Here are two examples of dynamic plots:

Manipulate[Plot[Cos[x],{x,-a,a},PlotRange->{-1,1}],{a,5,0.001}]

Manipulate[Plot[Sin[x+c]+d,{x,-7,7},PlotRange->{-3.5,3.5}],{c,0,3},{d,-2,2}]

Note the little + buttons next to the sliders in the above dynamic outputs. Clicking on one of those opens a navigation menu for that particular slider. The navigation menu allows us to see animated versions of the output, to find the current value of the parameter, or to set the parameter equal to a particular value. For example, we can see that setting the two parameters to c=1.57 and d=-1 in the second dynamic plot results in a sine curve that looks exactly as the graph y=cos x-1. (Try playing with the sliders to convince yourself in that!)

Although dynamic evaluations are a wonderful tool, they also require some care to avoid falling in certain traps. Consider the following dynamic plot.

Clear[f]
f[x_]:=Exp[-x^2]
Manipulate[Plot[f[x],{x,-a,a},PlotRange->{-1,1}],{a,2,4}]

We see a nice bell-shaped curve. Now let us take a look at another dynamic plot.

Clear[f]
f[x_]:=x Exp[-x]
Manipulate[Plot[f[x],{x,-b,b},PlotRange->{-1,1}],{b,2,4}]

If you go back and check your earlier plot (the one that was bell-shaped), you will notice that it has changed and now looks exactly the same as the latter plot. This is not a bug! Since both plots are supposed to present the graph of the function f(x) and are to be update dynamically, changing the definition of f(x) will result in both plots changing to match the new definition of f(x). For example, executing the commands

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

changes both plots above to dynamic plots of the parabola y=(x^2). Thus, when one wants to work with dynamic plots of different functions, one needs to name those functions differently. For example, the above commands should probably have been entered as

Clear[f1,f2]
f1[x_] := Exp[-x^2]
Manipulate[Plot[f1[x], {x,-a,a}, PlotRange -> {-1,1}], {a,2,4}]
f2[x_] := x Exp[-x]
Manipulate[Plot[f2[x], {x,-b,b}, PlotRange -> {-1,1}], {b,2,4}]

1.10 Additional Exercises

Exercise 8. Evaluate:
(a) (π^3)to 35 digits;		(b) (3^45);		(c) sin(0.8)/0.8.

Exercise 9 (Syntax error Jeopardy!). In this exercise, you are shown mathematical expressions and syntatically incorrect Mathematica code that purports to evaluate those expressions. You need to fix the given code, so it evaluates the respective expression correctly. Type your answers in cells of type Program, not Input.

(a) cos(1.2) to 20 decimal digits:	N[cos(1.2)];
(b) (Subscript[log, 3])(π):				log[pi,3];

For example, if the mathematical expression is ln(e) and the incorrect Mathematica code is Ln(e), your answer should be (note the type of the cell!):

Log[E]

Exercise 10. Define each of the following as a Mathematica function and plot it. Use graphing options as indicated.
(a)  f(x)=(x^3)-2x+2from-3to 3. Show the complete range.
(b) f(x)=(e^(-(x^2))) from -2 to 2; thicker than usual and in dark blue.	
(c) f(x)=x+5 sin x from 0 to 40.

Exercise 11. Find approximate solutions for each of the following equations by graphing two appropriate functions and finding their point(s) of intersection in each case. Use the GridLines->Automatic option.
(a) x=cos x in the interval [0,π/2].	
(b) sin((e^x))=(x^2)-1 in the interval [0,2].		
(c) ln x=3-(x^2) in the interval [1,2].

Exercise 12. When -5≤a≤5, the equation (x^5)-((a^2)+4)(x^3)+(x^2)+(a^2)x+2a+1=0 has 3, 4 or 5 solutions, depending on the value of a. Use a dynamic plot of the graph of the left side of this equation to determine the values of a for which the equation has:
(a) three solutions;		(b) four solutions;		(c) five solutions. 

Hint. If you are looking for roots, you only need to see the part of the graph that is close to the x-axis (but see it well). You may want to use the PlotRange option to help with that...

Credits

This lab is based on the laboratories created by Raouf Boules, Geoffrey Goodson, Ohoe Kim, and Michael O'Leary for use in the Calculus courses of Towson University. Commercial use is prohibited without permission of those authors. Non-commercial use is permitted, provided this credit section is retained.