UC SCI 111, vM
Appendix

Introduction to Mathematica

Mathematica is a general purpose package. That is, it can compute both numerically and symbolically. A special effort has been made to create good graphics capabilities.

Before we can play with Mathematica, we need to know about a Notebook and its use. A Notebook is a combination of  Mathematica input, Mathematica output and text. A Notebook is divided in cells. Look at the brackets in the right margin. They show the extent of various cells. A cell is at a given moment either input or output or text. You are reading text now. We end this cell here and start a new one with input in it:

4 5

Try to evaluate the contents of the above input cell. This is done by clicking the blue bracket in the right margin  (or any place inside the cell) and then typing <shift> <enter>.

If everything went right, you now see that 4 5 = 20 and you conclude that Mathematica views a space between two numbers as a multiplication sign. Now try to compute 4+5. Type your command between cells, for instance right after this one. You see a blue bracket appear, of the same kind as the one in the right margin of the earlier evaluation cell. Evaluate by the method you have learnt above.

We are almost ready to really start working with Mathematica. Below you see a number of closed cells. Open them one by one with a double click on the rightmost of the two brackets. The same method can be used to close cells again. Have fun!

An example session.

\(We\ are\ going\ to\ explore\ the\ function\ \ f\ \((x)\)\  = 
      x\^6 - 5\ x\^3 + 
        sin \((x)\)\ with\ \ \(\(Mathematica\)\(.\)\(
\)\((Evaluate\ all\ input\ cells\ as\ we\ \(go!!\)\ Things\ will\ not\ make\ sense\ if\ you\ don' \(\(t\)\(.\)\))\)\(\ \)\)\)
First the definition.

f[x_]=x^6-5x^3+Sin[x]

We ask for its derivative:

f'[x]

Then we have it plotted.

Plot[f[x], {x,-10, 10}];

Looks stupid. Another try:

Plot[f[x], {x,-1, 1}];

That is better.(?)

We plot the derivative.

Plot[f'[x], {x,-1, 1}];

Or both function and derivative in one plot:

Plot[{f[x],f'[x]}, {x,-1, 1}];

We would like to know the zeroes of f. One sees in the plot that they are near -1/2, 0, 1/2 respectively. We find them thus:

FindRoot[f[x]==0,{x,-1/2}]

FindRoot[f[x]==0,{x,0}]

FindRoot[f[x]==0,{x,1/2}]

Or, if you want more precision:

FindRoot[f[x]==0,{x,1/2},WorkingPrecision->40]

Zeroes of the derivative are just as easy:

FindRoot[f'[x]==0,{x,-1/2}]

FindRoot[f'[x]==0,{x,1/2}]

Exercise 1. 
a) Plot the graph of f(x) = (x^3)- 3 (x^2) -2 x + 7 and determine its zeroes.
b) Find maxima and minima of f.

Conventions. Capitals and brackets.

There are a few conventions that the uninitiated need to get used to. Like the fact that all Mathematica symbols start with a capital letter. Thus the base of the natural logarithme is not e but E. The idea is that all your own symbols start with a small letter, those of Mathematica with a capital letter. Stick to that rule and you avoid a lot of trouble.

Then there are all these brackets. Mathematica knows about the folowing ones.

De opening brackets (, {, [ with their respective closing brackets ), }, ] and the composites [[, (*, closed by  ]],  *).

({{bracket, meaning, example}, {., ., .}, {(, grouping, doThis := (x = (a - b) c; Print[x])}, {{, list,  littleList={3, some junk, 
              x = (a - b) c} }, {[, argument, Sin[x]}, {(*,  comment ,   }, {[[, index, littleList[[2]]}})

Let us make a shopping list:

needed = { flour, eggs, milk }    (* we are going to have pancakes *)

Print["First to the milkman for ", needed[[3]] ]

andnext := (Print[needed[[1]]];two = 1+1;Print["and"];Print[two," "needed[[2]]])

andnext

Observe that comma's serve to separate, while semicolons serve to put things consecutively.
In the command

	needed = { flour, eggs, milk } 
	
one introduces a list with three entries, but in

	andnext := (Print[needed[[1]]];two = 1+1;Print["and"];			Print[two," "needed[[2]]])
	
one defines 'andnext' to be equal to some things after each other.

Exercise 2.
a) Make a list containing the sine, the cosine and the tangent of π/3.
b) Use the Mathematica function N to compute the numeric values of the elements in your list.

Defining functions.

A function is defined in the following manner.

f[x_,y_]:=Sin[x]+y

Pay attention to the _ in the left hand side of f[x_,y_] := Sin[x]+y. It is needed  in the definition, but after that you should never use it! In the sequel one just types  f[x,y] or f[t,u] or whatever. 
The meaning of x_ is: we do not mean the symbol x itself, but what will be put in this place. Any x in the right hand side is to be replaced by whatever is put in the place indicated by x_. One calls x_ a pattern (Pattern) with name x. That is entirely different from the ordinary symbol x . The ordinary symbol x is just itself and belongs to the user as it starts with a small letter. Mathematica has no preconceptions about things that belong to the user. It has no right to guess that you mean a variable. For Mathematica x is no different than any other symbol like f or littleLamb. 
If you give a definition f[x,y]:=Sin[x]+y,  then  you should mean by that that f[x,y] is to be replaced with Sin[x]+y only when you type exactly f[x,y]. Literally with the symbols x,y in it!

For  Mathematica  our definition f[x_,y_]:=Sin[x]+y is a rule associated with f. Mathematica  does not mind if other rules are associated with the same f, as in

f[z_]=7

If we ask about f, it turns out Mathematica has rememberd both rules!

?f

f[8]

f[1,2]

Better take care then. With

Clear[f]

one gets rid of the rules associated with f. Check this by asking for information about f again.

Immediate and delayed assignments.

In Mathematica

lefthandside = righthandside

is an immediate assignment and

lefthandside := righthandside

is a delayed assignment. In

a = b

the b has to be computed immediately and the answer, say bnow, is put in the rule that in the future a has to be replaced with bnow. In contrast

a := b

means that right now a rule has to be associated with a saying that in the future a should always be replaced with b. (And then b has to be evaluated each time this happens. So what has been `delayed' is evaluating b.) Predict the answers to the following sequence of commands

b = 8
a := b
c = b
b = 3
a
c

Exercise 3.
Someone wrote the following code for factorial, with the intention that factorial[n] would return n! Correct the code so that the error message is avoided and so that factorial  works as intended for positive integers.

Clear[factorial];
factorial[n_] = n factorial[n - 1];
factorial[0] = 1;

In this Exercise you may exploit that if you give several rules for factorial, Mathematica  tries them in a definite order. To find this order, use the query

?factorial

The Mathematica help system.

For information about Mathematica  there is of course the manual (a fat volume). You may buy it in a shop, but you may also consult it through the online help system of Mathematica. 

You get there through the Help menu: click on Help in the menu bar. Click once more on Help. You get a window with an empty box, a row of indices and a browser. 

In the empty box you can type the word that you want information about. Say you have selected Built-in Functions by clicking. Then if you type the first few letters of Integrate, the following topics pass by:   I, the Mathematica  notation for the square root of -1, In, the Input symbol, Integer, meaning whole number, and finally Integrate itself. If you did not select  Built-in Functions before you started typing, then something else may happen.

Use the row of indices to select where you want to search. The index Built-in Functions contains all commands Mathematica  knows already, like Integrate. Particularly useful is the master index, the mother of all indices containing all existing search entries. 

Once you have a feel how Mathematica  has been set up, you may also use the browser to jump quickly to your topic. 
 
But you can also ask questions within the Notebook:

Have a look what happens if you type ?*ntegr*

?*ntegr*

Note that the user just typed ?*ntegr* and that Mathematica adds an In[ ] prompt to it. What the user wanted to know here is what commands are similar to Integrate. This kind of query is reasonable because the designers of Mathematica  have taken great care to use long descriptive names for commands. Next she was curious what NIntegrate is, and typed

?NIntegrate

After you evaluated this, you may have guessed that N stands for numerical. See if you can find examples to confirm this conjecture.

You get even more information about a builtin function when you use two question marks:

??NIntegrate

Later you will hopefully learn to use use this extra information.

Exercise 4. 
a) Plot the graphs of f(x) = sin(x) and g(x) = x  in one picture.
b) Use Mathematica and the help system to find the limit, as x approaches zero, of the function f(x)/g(x).
c) Does this match your expectations?

Loading a file into Mathematica.

For loading a file the usage is

<<filename

Make an ordinary text file example . m containing just the line

2 + 3

The recommened way is to use a plain editor. If you insist, you can make Mathematica emulate a plain text editor in the following manner. Open a new Notebook: click on File, New. Type your text in the new Notebook. We now want, exceptionally, to save the result as plain text, not as the Notebook it presently is. Use in the menu the  File, Save As Special..., Text option. Save the file in a reasonable directory, for example C:\\Mathematica. Observe that you have now destroyed the notebook as a notebook. So if you are the absent minded type this is not a great habit to teach yourself. Using text editors to make text and Mathematica to make notebooks is a much safer habit.

\(If\ you\ have\ to\ load\ a\ file\ from\ a\ directory\ that\ is\ not\ in\ the\ Mathematica\ search\ path, \ 
    then\ you\ have\ to\ give\ the\ path\ too, \ like\ this\)

<<Mathematica\example.m

Load your file in this manner. You find that Mathematica considers the contents of the file as something to be evaluated just like if the file were an input cell. You get the answer 5. (If not, start over). 
If later you write programs or have a long list of commands to evaluate, you probably want to put them in a text file rather than a notebook.

A different way to get a file into your notebook is through the menu. Click File then Import... then select example.m and the contents appear in your notebook, but now unevaluated. Try it. Almost the same happens when you use two exclamation marks, as in

!!Mathematica\example.m

The convention is that files with Mathematica programs have extension m while Notebooks have extension nb. Older Notebooks have extension ma. You may run into one of these dinosaurs.

Exercise 5.
Make two files, say name1.m and name2.m, so that both display your full name under 
	<<name1.m
and
	!!name2.m 
respectively.

Options.

Many builtin functions have options that modify their behavior. If you want to use an option, you give it as the last argument. An option always looks like a replacement rule. Example:

Plot[ Sin[x] , {x,0,2Pi} , PlotRange->{0,1} ];

makes that only values between zero and one are shown. Several options can be combined:

Plot[Sin[x],{x,0,2Pi},PlotRange->{0,1},Frame->True ];

In the section about the help system we saw the command

??NIntegrate

That way you find the default settings of the options of NIntegrate. You could also have asked

Options[NIntegrate]

Exercise 6.
Plot the function f(x)= sin(x) + x  on the intervals  [0,24π] and [0,1000π], first in the standard way, then with option PlotPoints -> 40. What is your analysis?

Simplifying.

Because Mathematica can also work symbollically, the user is bound to encounter the difficulty that things that are mathematically equal may yet look different. For example, let us take the primitive of (1  + (x^3))/(1  -  (x^3)) and differentiate the result. According to our school teacher the result should be the original  (1  + (x^3))/(1  -  
            (x^3)). However, if we actually do it, we see the following  (try your own variations!).

di =  D[Integrate[(1 + x^3)/(1 - x^3),x],x]

That looks entirely different. When we ask Mathematica if this is the same, the following happens:

% ==  (1  +  x^3)/(1  -  x^3)

That is the Mathematica  way of saying: don't know. (It evaluates the question and then returns where it got.) Incidentallly, that is what it always does. It evaluates until it has no more applicable rule and then returns the resulting expression. The symbol % indicates the value of the last output. Did you guess/find what == means?

We can ask it to use common denominators:

Together[di]

That is already closer to (1 + (x^3))/(1 - (x^3)).  We try some more: We apply Together also to the original function.

Together[(1 + x^3)/(1 - x^3)]

Not quite. What about factoring?

Factor[di]

That looks promising.

Factor[di]==Factor[(1 + x^3)/(1 - x^3)]

At last! It would have been more clever to investigate the difference:

Together[di-(1 + x^3)/(1 - x^3)]

It is all a matter of practice. 
Use the help browser to find some functions related with Factor and Together. Now that we have a topic, the help browser is the right tool.

Exercise 7.  
Compute zeroes and critical points of the function 

	f (x)  =  
        1  -  (3/(2 (x - 1)))  +  (3/(2 (x + 1)))

Solving equations.

One equation.

Mathematica has a function Solve for solving (systems of) equations. When you plot the function f (x) =  (x^(3 )) - 7  (x^2) + 13  x - 4 and the line g (x) = 2 x + 1 in in one picture, you see that they clearly intersect in one point and are perhaps tangent to each other in another point.

f[x_] = x^3 - 7x^2  + 13 x - 4

g[x_] = 2 x + 1

Plot[ {f[x], g[x]} , {x,-7,7} ];

The function Solve solves equations. We may therefore ask Solve to compute where f and g coincide:

soln = Solve[ f[x]==g[x], {x} ]

Apparently f and g coincide in x = 1 and in x = 5. But in x = 1 more is going on. Could the derivatives be equal?

( f'[x]==g'[x] ) /. soln[[1]]

Yes! What exactly did we do here? Solve returns a list with in it three times a list with something that has an arrow in it. We wish to use the first solution now. So we must use soln[[1]], which reads {x→1}. (It happens to contain a 1, but that is an accident. The 1 from the expression soln[[1]] is a different 1.)  You may recall that the arrow → indicates a replacement rule. (We used them in options.) If we replace x with the value after the arrow, we get a solution. The /. stands for replace all. Thus our input command ( f'[x]==g'[x] ) /. opl[[1]] asks to replace every occurence of x in the equation f'[x]==g'[x] with 1.

You can name the three solutions of f[x]==g[x] like this:

{zero1,zero2,zero3}=x/.soln

zero3

Another way:

zeroes=x/.soln

zeroes[[3]]

A system of equations.

According to the usage of Solve, we can feed it more than one equation:

?Solve

But then one had better understood what is meant with the usage Solve[eqns, vars]. The second argument of Solve must be vars, not the second equation from eqns. So this is wrong:

Solve[ x+3y==5, x-5y==7, x, y]

And this is right:

Solve[ {x+3y==5, x-5y==7}, {x, y} ]

In any similar situation you should always use lists to ensure that the first argument contains what is expected in the first argument, the second what is expected in the second, and so on.

Repeating.

Mathematica has a rich programming language. So it certainly has constructs for repeating a Exercise. The simplest is the While construct and the most general one the For construct. An example.

i=1;While[ i<9 , silly;nonsense;Print[i];i=i+1 ]

Mathematica does not recognize the commands silly and nonsense. That is no problem, because if it has no applicable rule, it just leaves it as it is. Mathematica  does not distinguish commands from other expressions. Anything is evaluated until there is no more applicable rule.

Exercise 8.
a) Change the while loop from the example in a for loop that yields the same result. (Use  the help system!)
b) Compute 10! with a while loop.

Conditions.

The

/;

in

f[x_]  :=  Sin[x]  /;  x > 0

means `provided that'. Find out how  If works.

Exercise 9.
a) Plot the graph of f  in the interval [-π, π] and explain the result.
b) Define a function g(x) so that

	g(x) = sin(x)  if x > 0
	g(x) = x         if x < 0
	
Check your solution by plotting g.
c) What is g(0)? How would you define g in x = 0?

Modules and local variables.

A larger program is developed and tested in little pieces. To combine these pieces, called modules, without hassles it is necessary that the modules do not interfere with each other. A module needs its own space to work in, space that is off limits to outsiders. That is why a module uses local variables. Such variables have, so to speak, not just a first name (the name used by the programmer) but also a last name which is added by the machine to keep track of the module the variable belongs to. (More precisely, the `last name' also encodes which particular call of a module the variable belongs to.) By making them local to a module, favorite names likes  i,  x, f, temp can be used without worry in several places. We made an example file called silver.m in which you can see a module in action. Read it and investigate if it does what it claims to do. You may try to do the exercise at the end of the file.

Packages.

A package is a coherent set of definitions, collected in a file. Many functions that are only of special interest have been put in packages. If you want to use a function defined in a package then you have to load the package right at the beginning.

Say C is the curve given by the equation (x^2) + ((((y^2) - 1))^2)  = 1. If we wish to plot C based on this equation, we need the function ImplicitPlot, which lives in the Graphics`ImplicitPlot` package. Make sure you do not use the symbol ImplicitPlot before you have loaded the package. If you mistakenly introduce a symbol before you have loaded the appropriate package, you get a mysterious error message with the word shadow in it. Better start a new session (of the kernel).

Needs["Graphics`ImplicitPlot`"]
ImplicitPlot[(x^2)  +  ((((y^2) - 1))^2)  ==  1, {x,-2,2}];

Instead of using Needs, you can also use << to load the package, as a package is just an ordinary text file with a Mathematica program in it. Thus:

<<Graphics`Graphics`

In the Add - ons index of the Help menu you can find all standard packages and the functions that these packages make available.

Exercise 10.  
Find the distance from Washington D.C. to Moscow.

Extra exercises.

1.  Compute  (((e^(π (Sqrt[163])))  - 744)^(1/3))   in ten digit precision .  What  is going on?

2.  Determine the points of intersection of the  hyperbola 

	(x^2) - x  y - 6  (y^2) = 4

and the ellipse 

	(x^2) + 3  x  y + 4  (y^2) = 7. 

\(Also\ give\ the\ points\ separately . \ \((Not\ just\ wrapped\ in\ rules\ or\ \(\(lists\)\(.\)\))\)\)

3. A road runner has ended up between two trains that approach each other with constant speed. The road runner runs with a speed of 153 m/s to and fro between train A, which travels with speed 60 m/s to the right and train B which travels with speed 40 m/s to the left. At t = 0 the distance between trains A and B equals AB. And the road runner happens to be at train A. At which moment does the road runner stop running?

4. Write a function factorial, so that factorial[n] returns n! when n is a positive integer, and so that negative numbers do not cause an error message.

5. Adapt the function factorial form the previous exercise in such a manner that it only returns an answer if that answer has fewer than 100 digits.

6. Implement a function pascal so that pascal[13,7] is, for instance, the seventh entry in the thirteenth row of Pascal's triangle. Start your numbering with zero. So row zero contains just one 1. And in row seven the entries run from entry number zero to entry number seven. 
                                    1
                                  1   1
                               1   2   1
                             1   3   3   1
                           1   4   6   4   1
                         .    .    .   .     .    .

7. Compute the determinant of the matrix

(({{1, a, (a^2), (a^3)}, {1, b, (b^2), (b^3)}, {1, c, (c^2), (c^3)}, {1, d, (d^2), (d^3)}}))

and factor the answer. Try variants.

8. Compute

\(TraditionalForm\`\(\(	\)\(∏\+\(n = 1\)\%500\((1 - q\^n)\) + 
      O\ \((q)\)\^500\)\)\)

That is, the product of the 500 factors is to be expanded and then all terms need to be thrown away that involve powers of q that  have exponent 500 or higher.  Can you get the same answer without computing many unnecessary intermediate results?

9. Programming is an art. See the file zilver.m

10. Again an exercise that requires more. Mathematica  ``does not stick to the  syllabus''. You should not be shocked when Mathematica  uses complex numbers, Bessel-functions, etc.
Determine by means of Mathematica the primitive f of

	(((x^6) + 1)/((x^6) - 1))
	
Is this f real valued for x=3?
For x=0?
How is that possible? What would be your favorite choice of primitive for |x|<1?

Further browsing.

The online Mathematica book contains a practical introduction where you find more about topics we have touched upon only briefly, or not at all. You ought to be able to locate this introduction easily. 
You can admire a collection of pictures, sounds and spectacular applications in the  Mathematica Gallery