Introductory Mathematica Tutorial
Bradley Matson, Western Oregon University
Lesson 1: Getting Started with Mathematica - The User
Interface
Download tutorial 1 (**not
operative**) and read through it to familiarize yourself with it. Here are some key
hints:
A note about printing mathemanica files: Mathematica uses postscript commands to
justify fonts and render graphics. If you don't have a postscript printer this can be a
problem. Any HP DeskJet printer will interpret the postscript commands as will many
higher-end laser printers. At WOU, we don't have highend laser printers (figures), so
print to the InkJet printers.
- A mathematica notebook (like the thing you downloaded) has an extension '.ma'. Its
really only a text file with certain commands for mathematica to interpret. (Graphics are
rendered in Postscript commands.)
- Text in the notebook file is broken up into 'cells' (and perhaps sub-cells grouped
together). Cells are indicated by the blue bracket on the right side of the screen.
- To select a cell (or cells) click on the cell with the cursor (or click on the first
cell, move to the last cell, and then 'shift-click' on the last one).
- Cells may contain several different styles including 'input', 'output', 'sub-section',
'text', 'message', etc. Each cell type has its own font. (For instance 'message' styles
are in red as they are warning or error outputs from mathematica.)
- The cell type is shown in the pull-down menu just under 'File Edit Cell' at the top of
the screen.
- You can copy just part of the text in a cell in the usual point-and-select method you
windows users are accustomed to. You can also copy blocks of cells using the copy-paste
method.
- There are 'cell action' types too. (They are identified by the shape of the blue bar.)
For instance, user-written comments in the form of text, sub-sections, titles, etc., are
'locked' cells. Locked cells cannot be executed. There are input cells which can be
executed. To check or change the cell action type, highlight the cell (or cells of the
same type), and select Cells (from the main menu). There are 'initialization' cells which
can be executed when a file is first opens (or by going to 'Action' from the main menu
under 'Evaluate Initialization'). This feature can save much time!
- To evaluate a cell either place the text cursor in the cell or highlight the cell (or
cells). Then press 'shift-return' (or is that 'shift=enter')?
- Placing a semi-colon at the end of a statement suppresses it from printing out.
Executing ' x = 5 ' would result in mathmatica reporting 'x = 5'. Sometimes that's a
little redundant and messy, so we can execute ' x = 5 ; ' and nothing is printed.
- You can separate long equations onto new lines, but be sure that the end of the previous
line ends in an operator (+, -, *, /, . , &, ^ ) or a delimiter (a comma or
semicolon).
- To insert a cell between two existing cells, position the cursor between the cells until
the horizontal bar cursor appears. Click the mouse there and a large horizontal bar
appears. Start typing.
- Print out the notebook 'tutor1.ma'. I want you to write on this print out and turn it in
with your answers. On the print out, number each cell and for each cell, answer these:
- How many statements are in the cell?
- How many lines are in the cell?
- What is the style of the cell?
- What is the cell's action type?
- Execute the first three cells (from 11*3 to 67842 * 83932 * 573285/( 45689 + 586490)).
Fast, huh? Look at how the outputs are displayed. Are they correct? Check them with a
calculator. Notice that the 'kernal' loads first. It only needs to load once per session.
To verify that, execute them again. Much faster this time!
- I didn't really mean to type the cell with x = 57 and y = 67. Delete this cell.
- The three cells the give assignments to x, y, zz, and z, I meant to be 'grouped'
together since they perform the task of setting important values. Highlight these cells
and 'group' them by either selecting Cells, Group from the main menu or just press . The
individual cells can be selected by using the blue bars towards the inside on the right
part of the screen. The entire group can be selected by the longer blue bar towards the
outside. Clear?
- I suppose this group of cells ought to be the first things executed when a user opens
and begins fiddling with this file. Move (cut and paste) the grouped cells just above the
first 'input' style cell. (Don't do it by moving each cell individually - move the whole
group!)
- Furthermore, I think this group of cells should be initialization cells as that is their
purpose. Make the grouped cells so.
- For fun, lets see what happens when you close then re-open the file. It should ask you
if you (really) want to execute the initialization cells. Say yes.
- Execute all the cells up to (but not including) the Postscript cell. Check them against
a calculator. Look carefully at them. Where's the answer to y2? Fix this cell
and execute it so that you can get a value for it.
- There are some cells under the subsection (not the subsubsection) cell. Which cell
defines the function, as we might write it in a textbook, f(x)?
- The very last cell puts 'values' in for f(x). Don't execute this cell, yet! Predict what
the outcome will be when you do execute this cell. No cheating!
- Now execute the cell. Were your predictions right? If you followed these instructions,
you prediction should be wrong. Why?
- Fix the problem and execute this very last cell again. Now are your predictions correct?
- Hmmm.... We never defined 'a'. I want it to be with the initialization group in its own
cell between the cell defining zz and the one defining z. Insert the new cell and type
into it 'a = 3 '.
- One last time, execute this very last cell. Do you get what you expect? Explain.
- Find the cell that assigns 'SomeJunk'. Decompile this statement and write it as a
textbook might.
- Lastly, you can interrupt the execution of the cell. Clearly, the 'SomeJunk' statement
is going to take a long time. Perhaps you want to modify (and make it execute longer!) and
don't what to wait around for 26 hours. To stop it use the 'hand-up-to-stop' icon on the
toolbar. A window gives you choices. You can continue (with the execution), abort the
execution but retain the kernel in tact. This allows you to see partial results and retain
all the assignments you have made previously. (Sometimes Windows will shift the order of
the open windows around and hide the mathematica window - thanks Bill.) If things have
really gone wrong, select 'quit kernel' and, although you will lose all assignments and
have to begin again, you can save the file and not lose any work (with luck).
Okay, this was pretty boring, but you needed to learn how to use the mathematica
interface. Please print out the notebook file once again and hand it in with any written
comments you've made.
Lesson 2: Getting Started with Mathematica - Built-in
& User Defined Functions and Simple Plotting
Download tutorial 2(**not
operative**) and look it over quickly. No need to print it out again unless you want
to. Here are some key concepts.
- Mathematica has built-in functions which always begin with a capitol letter. Arguments
of all functions (built-in or user-defined) are always in brackets '[' and ']'. (For
instance, sin[ 3.14 ] is expected to be a user-defined function, but Sin[3.14] will be
'the sine of 3.14'.
- Mathematica will always try to do computations analytically unless you tell it otherwise
using the N[ expression ] function. (For instance, evaluating Sin[3.14] will return
'Sin[3.14] ', but evaluating N[ Sin[3.14] ] will return 0.00159265. Hint: For more
accuracy try N[ Sin[3.14] , 10] , which gives the result to 10 decimal places!)
- Functions like ex and p have these
special symbols: E^x and Pi. (We use a capitol 'E' in keeping with the rule that built-in
functions always start with a capitol letter.)
- The mathematical symbols ¥ is 'Infinity', the
integral is 'Integrate', and the ¶r
symbol is simply D[ expression, r ].
- Feel free to place extra spaces or tabs into a notebook file. Mathematica will ignore
extra spaces. In fact, it is desirable to add extra spaces to 'format' you work so it is
easier to read, troubleshoot, and work on.
- The '=' is the assign, but the '= =' is the 'equivalent to ?' operator (see below).
- Conditional (If) statements can be tricky. Suppose you want to see if x and y are
equivalent, and if they are return one and a zero otherwise. You don't use the statement '
If[ x = y, 1, 0] '. If you tried this first x would be assigned the symbol y (or its value
if there is one), and - arg, you have a recursive loop. Instead you use the 'equivalent to
?' operator, that is the statement would read ' If[ x = = y, 1, 0] '. There is the logical
OR operator ' || ' and the logical AND operator ' && ' as well. The other ones are
as you might expect, (I.e., greater-than-or-equal-to is just ' >= ').
- Don't use underscores in your variable names! The underscore is reserved to indicate
unspecified input. For instance, the function definition for f(x) = sin(x) would be
written as 'f[ x_ ]:= Sin[ x ]'.
- In the above warning, watch out for this trap. Function definitions are made with the '
: = ' combination, not just an ' = ' sign. (p.s. The is just the reverse of Maple!)
Please don't execute this notebook yet. You have some changes to make first!
- A bit of review: In the first two lines, what is the difference between the cells? If
you executed both of them, what will be the result. Write it down to be turned in!
- In the cell after Review 2, what will be the differences in how the 8 statements will
execute? Predict what their output will be.
- Look at Review 3. Rats, I meant to made the cell containing Review 3 a subsubsection
style like the rest. Please change it.
- Now look at the cell below review 3. Fix them so that a*b*c will operate correctly.
- Execute the cells from review 1 through 3, fix any errors, and execute them until each
statement gives the hoped for answers.
- Insert a new cell directly after 'Using the Built-in functions' subsubsection.
Numerically evaluate these and check them with a calculator. (remember I want numbers -
fractions are okay) You may wish to put each of these below in its own cell and group
them!
- the natural log of 2.71828
- the natural log of 7
- the natural log of 0 - does this surprise you?
- Use the help files and compute the Log base 2 of 65536
- the sine of 22 degrees. Hmmm, this might take some thought!
- the inverse (arc) cosine of 0.4 in degrees
- the (natural) exponential of 2.05
- Square root of -4
- Make a new list of cells below those you just did evaluating these analytically
(remember, I want p left as 'Pi , etc.) :
- inverse (arc) sine of the square root of 2 over 2.
- the sine of p/4 radians.
- the fraction that the hypotenuse of a 3,4,5 right triangle make with the hypotenuse of a
right triangle with two shorter sides of 132 and 156.
- Separate the cells you made with a subsubsection with an appropriate title and group all
these cells together.
- Find the numerical value of the sine of p
times the square root of the sum of the natural log of 5 and the natural log of 6. (Don't
ask why.)
- Look over the two example functions after 'Defining functions'.
- Look over the 'Evaluating the function' section. Predict what the output will be if you
evaluate the two x[ ... ] expressions. Then evaluate them. If you didn't get what you
expected, explain why. Maybe you didn't evaluate the cells defining the function x[ ... ]?
- Note, its always a good idea to 'Clear' the functions before defining them. Create your
own functions to:
- Convert an angle in degrees to radians (in naming these, please be more creative or
logical than my examples!)
- Convert an angle in radians to degrees
- To compute the hypotenuse of a right triangle given the other two sides.
- The area of a sphere its given radius.
- To convert a complex number (one with a an i - the square root of -1 -- in the
form x + iy into the exponential form r ei q, where r = (x2 + y2)½
and q = Arctan( y/x) .
- A function of x and y that will return -1 if xy, and 0 if they are equal. (Nesting
required!)
- The volume of a box given its height, width, and depth.
- Make up your own values to plug into the function you defined above. Check them with a
calculator if you aren't sure they are right. Its always a good idea to first try from
unspecified variable such as a, b, or c (or whatever) to verify what you entered is what
you think you entered. Then try a numeric value. You probably want numerical answers
rather than analytical ones. One way to simplify this is to include the ' N[ ... ] ' in
the definition of the function. Such as MyFunction[ t_] : = N[ 7 * Log[ 2 + t] ], which
will always try to return a numeric answer. Beware, though, many times we WANT analytical
answers!
- Lets try some simple plotting. Throw away those graphing calculators and watch the power
that oozes forth. Using the example provided to plot x[y], try your own functions,
especially some of the more interesting ones. Judicious use of the cut and paste may be
useful. Note that in the declaration of the range {y,0,10} from my example, you can use
any (dummy) variable there such as ' Plot[ x[ thisisadumbvariable], {thisisadumbvariable,
0, 10}]'. Try your own ranges such as {y,-max,max}, where you define 'max' a statement
before (the 'Plot' command). Indulge yourself. (If you can't see all the plot, see below.)
- Finally, plot your favourite function directly. Mine is the Gaussian function, and I
love to do this:
Plot[ E^(-x^2), {x, -10, 10}, PlotRange -> All].
The 'PlotRange->All' forces the plot to adjust the view so all points can be seen.
I'll show you some more advanced plotting techniques later.
Please print out the notebook file once again and hand it in with any written comments
you've made.
Lesson 3: Getting Started with Mathematica - Linear
Algebra: Vectors, Matrices, Lists, Tables, and Manipulations
Download tutorial 3(**not
operative**) and lets take a gander. Note I've defined matrices M1, M2, M3, and
vector V1. Here are some key ideas:
- Arrays and Matrices, Lists and Vectors use braces '{' and '}' to separate elements. A
1-D matrix (or a list) is otherwise known as a (row) vector, v, could be written in a
textbook as v = (3, 5, 10). In Mathematica one writes ' v = {3, 5, 10}.
The
matrix
would be written as m = {{ 11, 12, 13}, {21, 22, 23}, {51, 31, 33}}. This is what they
call 'row-column order' for the obvious reasons.
- Vector algebra is fun and easy! Consider the vector, v, and matrix, m. The product of
the vector and matrix is ' m . v '. Note the 'dot' is used for the 'dot product'. For two
vectors, this is important. The scalar (dot) product is Dot[ v1, v2]
and the vector (cross) product of v1 with v2 is Cross[v1,
v2]. Two matrices are multiplied with the 'dot' also: m1 . m2
is the matrix product of the two matrices m1 with m2 .
- To extract or assign individual elements in a matrix you use double brackets '[[' and
']]'. In the matrix above, the element with the value 51 is in column 1, row 3, so that
executing ' m[[1,3]] ' would return 51.
- A list (be it a dumb o' list, a vector, an array, a matrix, or whatever) begins with
element 1. Thus the first element of ' m' defined above is extracted like this: m[[1]]. IF
you are a C programmer you'd think that the first element starts with index zero, but you
get an error message if you do this: m[[0]].
- A 2-D list (usually called a matrix) element's first element would be m[[ 1, 1 ]] and so
on.
Lists:
- Here's a list of ugly numbers. Please create a cell that, when you execute it, it puts
this list into the variable called ' list1 '. Put it right after the ' Simple Lists '
section.
{0, 0.309017, 0.58779, 0.80902, 0.95106, 1.00000, 0.95106, 0.80902, 0.58779,
0.309017, 5.6660*10^-16, -0.309017, -0.58779, -0.80902, -0.95106, -1.00000, -0.95106,
-0.80902, -0.58779, -0.309017, 1.53133*10^-15, 0.309017, 0.58779, 0.80902, 0.95106,
1.00000, 0.95106, 0.80902, 0.58779, 0.309017, -(3.1852*10^-15), -0.309017, -0.58779,
-0.80902, -0.95106, -1.00000, -0.95106, -0.80902, -0.58779, -0.309017, 4.8390*10^-15,
0.309017, 0.58779, 0.80902, 0.95106, 1.00000, 0.95106, 0.80902, 0.58779, 0.309017,
5.9416*10^-15}
(Judicious use of cutting from this HTML document and pasting to the notebook will save
time typing. Some editing may be required after pasting, however.)
Tables and Plotting Lists:
- The data I gave you above for ' list1 ' is actually a familiar function. You can see
this by plotting it. In a previous PS, you plotting an analytical function using ' Plot '.
However, this is a list of discrete points. To plot a list you use the (obviously named) '
ListPlot ' function. Plot ' list1 '. The syntax is ' ListPlot[ list, options '
where some of the options are ' PlotRange -> All ' or ' PlotRange -> {{ xmin,
xmax,},{ymax,ymin}} ' and ' PlotJoined -> True ' and you can even add labels using the
options ' AxesLabel -> { "x label", "y label" } ' and PlotLabel
-> { "title" } ' .
- Try out some the various options. Of course, there are more also, but these will satisfy
most of you plotting needs. Use the options to give you a line (not individual points),
appropriate labels on the axes, and a fitting title of the plot.
- The list ' list1 ' you entered would be a real pain to type in by hand. There must be a
way to create long lists and the ' Table ' function is good for that. (There is also the '
List ' function, however the Table function does the same thing and more.) In fact, I used
the Table function to create ' list1' initially. Type this into a cell and see how ' list2
' compared with ' list1 '. Create your own method of comparison and write it down to be
turned in.
list2 = Table[ N[ Sin[x] ] , { x , 0 , 5 Pi , 0.1 Pi}]
- Create your own list using the Table function that will give a list of values of the
tan(x) from 0 to 6 p in increments of p/10. Let's place this list in a variable called '
list3 '.
- Plot ' list3 '.
- I anticipated you had troubles. Try limiting the plot range between -10 and 10 by
indicating ' PlotRange -> {ymax,ymin} ' as an option. I think that connecting the point
with a line might help you see the plot also. Fix the plot.
- Look carefully at the plot. What I really wanted you to do is provide a graph that shows
tan(x) in the range 0 to 6 p, but the horizontal
axis doesn't jive. The plot simply shows the tax(x) versus the data point number (and
there are 61 of them.) Fix this by making a list of 2-D vectors rather than a 1-D list of
scalars. Change the argument in the Table function from a scalar to a 2-D vector
containing the x and the tan(x). Questions? Fix the list and the plot (if you can)!
- Does the plot really look like tan(x) vs. x? Explain why not.
- Fix the plot by adding more points and I think you will want to use a ' ; ' at the end
of the Table function to prevent it from printing out hundreds of numbers. Experiment with
how the number of point affects the plot's quality. Make your final plot really nice - but
don't wait forever to get it either!
- Now have a little fun and create a 2-D list and an accompanying plot for one of these
functions:
- BesselJ[8,x*50]
- BernoulliB[8,x * 10]
- BesselI[4,x]
- Beta[4,x * 0.9 ] (this one has trouble at x = 0, but Mathematica can handle it!)
- ChebyshevT[10,x ]
- EllipticK[x ]}
- Or your favourite function!
Do them for the range of x from -1 to 1 in steps of 0.001
Vectors
You remember this! A 2-D vector is a representation of a point in space
which tells you is x and y position on some coordinate system. With x and y you know the
distance to the point as r = ( x2 + y2)½ and the
direction in terms of the conventional angle qc
= arctan( y/x ). The way we write it a textbook is
and, look, it looks just list a 2-D list! Create a cell that defines the vector ' v8 '
that represents a point with x value 3 and y value 4 (sound familiar?). Create a second
one, calling v9 with x value 2 and y value -4.
- This is an analytical step - do it on paper or directly in mathemetica Compute the
length of v8 and v9. Compute the sum of the vector v8 and v9. (This is done by adding
components separately!)
- Now let's use the power of mathematica's built-in functions. Remember that the magnitude
(length) of a vector is |v| = ( v.v )½, where the ' . ' is the scalar or dot
product. Use Mathematica to compute the magnitude.
- The scalar product of two vectors gives the length of the projection of the first on the
second. Try this out by computing the dot product of two parallel vectors and two
perpendicular vectors. Be sure the two vector are of the same length!
- You can also use the vector or cross product. Remember that from E & M? Underneath
"Explore the Cross Product section" there are four 3-D vectors defined (they are
v4, v5, v6 and v7. Write them down as a textbook would.
- Predict what these magnitudes are and if the cross products of the combinations below
should be zero or non-zero.
v4 ´ v5 =
- v5 ´ v4 =
- v4 ´ v6 =
- v4 ´ v7 =
- v5 ´ v6 =
- v5 ´ v7 =
- v6 ´ v7 =
- v5 ´ v5 =
- v6 ´ v6 =
- Now have mathematica do it using the ' CrossProduct[ v1, v2 ] ' function. Any surprises?
(You may need to execute ' << Calcuclus'VectorAnalysis ' first depending on the
version of mathematica you are running.)
Matrices:
- Execute all the cells between the 'Simple matrix algebra' section and the 'Your work
goes here' section. Look at them carefully and learn!
- Move below the 'Your work goes here' section and insert cells as the rest of the PS
asks.
The identity matrix is defined as the matrix who's matrix product with
any matrix M is M (again). Type in an expression for the 4x4 identity matrix:
Create an expression for this 4x4 matrix
- To check to see if you typed it in right, compute the product of 'newMatrix' with
itself. It should be obvious that it was typed in correctly by this product (as long as
you read right to left).
- Show that the product of 'Identity4' and 'newMatrix' is 'newMatrix' again, just like it
should.
- Describe how you would extract the value 27.8747 from 'newMatrix' .
Please print out the notebook file once again and hand it in with any written comments
you've made.
Lesson 4: Getting Started with Mathematica - Calculus
- The mathematical symbols ¥ is Infinity, the
integral is Integrate, and the ¶ symbol is
simply D[ expression ].
- The integrate function
- The derivative function
Before you begin, get out a pen and paper (and maybe an old math book) and do these
question by hand!
- ¶x x3/3
- ¶x x2 y3
- ¶y x2 y3
Download tutorial 4(**not
operative**) Notice that the functions I had you compute above are defined and the
same operations I asked you to perform above are ready to be evaluated in this notebook.
Execute these cells. Please take the time to read the comments and learn how to do the
above operations in mathematica. These are the 'bread and butter' of computational
physics.
Note in the exercises below, you don't really need to define the functions first,
however I'd like you to do so as practice.
- Find the derivatives d/dx of
- x
- (x - 1)
- 1 - x-4
- ax - bx2
(a and b are constants left as they are)
- x2a (a is a constant)
- (10x2 - 1/15 x6) 4a (a is a constant)
- 1/(1 - x2)
- sin(x)
- cos(2x)
- sin(2x) cos(3x)
- e-9x
Find the partial derivatives of
- ¶x 5 y2 x3
- ¶y 5 y2 x3
- ¶x ¶y (-1) cos (y) sin(x)
- ¶x ¶y e-ay sin(x)
- ¶y ¶x x-ay
- ¶x ¶y ¶z
z-1/2 3-ay sin(bx)
With respect to x, find the indefinite integrals (also called the anti-derivatives) of
- 7
- x
- 3 x2
- (x - 1)
- ax - bx2
(a and b are constants)
1/(x2)
1/(1 - x2)
7 sin(x)
47 cos(x)
cos(2x)
sin(2x) cos(3x)
cos2(x) = [cos(x)]2
9 e-x
Find the definite integrals (with respect to x) of the following between the limits
shown.
- 3 x2 [-1,1]
- ax - bx2 [-1,1]
(a and b are constants)
1/(1 - x2) [1,2]
(x2)-1/2 [1,2]
cos(2x) [0, p radians] = [0, 180 degrees]
sin(2x) cos(3x) [0, p radians] = [0, 180
degrees]
cos2(x) = [cos(x)]2 [0,2 p
radians] = [0, 360 degrees]
9 e-x [0, Infinity]
Find the definite double integrals (with respect to x) of the following between the
limits shown.
- sin(x) cos(y), x:[0, p/2], y:[0,p /2]
- sin2(x) ey, x:[0, 2p],
y:[0,1]
- x2 + y2, x:[0,1], y:[0,1]
- e-x2 y, x:[-¥, +¥], y:[-1,1]
Lesson 5: Getting Started with Mathematica - Modules and
Programming
Wow! We have explored a lot of mathematica. Don't discount this a learning Mathematica
only (Maple, MathCad all use similar techniques and even syntax). In the process, you have
learned some of the basics of computational physics. There is a great deal more to learn.
Programming (not just defining functions and evaluating simple expressions) is a heart of
computation physics. More traditionally, programs are written in a compiled language such
as FORTRAN or C. Mathematica has a compiled programming form called 'modules'. Modules are
essentially programs. They can be treated as objects, sub-routines, or stand-alone
programs in themselves. The most important tool to programming (at least for computations)
are loops, which we also tackle here. One thing we won't investigate until later (maybe)
is the believability of computational models. Models are, after all, only approximations
under a specific set of conditions. Every model fails eventually and then the
computational results are not to be trusted - for garbage you get garbage out. I might
sneak in some of the test of believability of computational models under certain ranges,
but only as a secondary issue (if this were a computational physics course, I would
reverse the emphasis). Our main goal is to learn modern physics wholistically.
A program is a set is computer instructions which take input and generate output. Our
use for programming will be mainly to generate output from a model. For instance, lets say
the model is one for waves impinging on a slit (who's width is about the same as the
wavelength of the waves). In order to compute the intensity of waves at a point behind a
single slit , one must compute a 2-D integral. If you wanted to plot the intensity behind
such a slit at many points along a plane parallel to that slit, you would need to do a 2-D
integral for every point (that you want to) on the plane. Later you could make plot of the
intensity everywhere behind the slit! And, you know, this sounds like such a great
example, I'm going to have you work on it. In this case, we'll make the waves deBroglie
matter waves!
First, some examples and practice. Please watch the syntax, especially where the ' ;'
and ' , ' are placed at end of lines. These are critical!
Key Stuff:
- Loops are often required for computational problems. We have 'Do[ ]' loops in
mathematica. There are also 'While[ ]' loops. I prefer the former.
- The syntax for Do loops is: ' Do[ body of loop , { loop_variable, min_value,
max_value, step_value}]
- If there multiple lines in the body of a Do loop, each statement in the body must end
with a semicolon., execpt the last line. For instance,
Do[
addtoit = 2^i;
temp = data[[i + 1]] + data[[ i ]];
data[[ i ]] = data[[ i ]] * addtoit + temp,
{i,1,10}]
Of course, this could have been done in one statement inside the Do loop, but this was
only an illustration.
- Another important loop tool is the ' Sum[ ] ' function. It does pretty much what you'd
think; it does the summation of the expression contained in the body. Its syntax is the
same as ' Do '.
- Recall that a list (be it a dumb o' list, a vector, an array, a matrix, or whatever)
begins with element 1. Thus, in do loops that access individual elements of a list (e.g.,
a 1-D list m), the first element would be extracted like this: m[[1]]. If you are a C
programmer you'd think that the first element starts with index zero, but you get an error
message if you do this: m[[0]]. A 2-D matrix element's first element would be m[[ 1, 1 ]]
and so on.
- Programs in Mathematica are called Modules. A module has two input parameters and you
can chose the output parameter form. The syntax is ' Module[ { names of variables used
inside the module that are not to be shared with the outside , body of module ].
- Each statement in the body of a module must end with a semicolon, except the next to
last line (which ends without one). The very last line of the body will be output.
- The output is a list. If only one result is to be returned then there's no need to put
it in {}'s. See the examples!
Download tutorial 5 (**not
operative**) and my set of useful modules Useful.ma (**not
operative**)
Do loops
- For Each of the examples for Do and Sum loops, write out a description of what they do.
Directly under "Your Work Goes Here" write a Do loop that
'chops off' the list ' cosdata ' (its below.) It should look like this when you are done:
- Look over your description for Tapr. Create a plot of cosdata and newcosdata. Was your
description correct?
- How would you change Tapr so it uses linear function. Try this, but copy Tapr and rename
it Tapr2. Replot as required.
- Under the ' Create a list 'tse' which has elements of a taylor series ' (or more
correctly sequence " section, create a list of elements who have the values x,
x2/2!, x3/3!, ..., x20/20!. The factorial of n, is
written ' n! '. Be cleaver and define a function ElementsofE[x] that returns the list
'tse'.
- Create a new function ApprxE[ tse ] that adds up all the elements of 'tse' for an
arbitrary x. Perhaps you recognise that you are computing the power series for ex?
Try you a few values and compare them to your calculator (or Mathematica).
- Lastly, create a Do loop that prints out 'fractional error ' between ApprxE[
ElementsofE[x] ] and E^x from x: [0, 100] in steps of 5. (That is print out: ( ApprxE[
ElementsofE[x] ] - E^x )/E^x )
- Think carefully about how computers actually make computations. How do you suppose a
computer internally computes ex? Can a computer be perfectly accurate? Why or
why not?
Under 'Create the norm function for a list', create the norm function
for an arbitrary list. Actually there are many types of norms. Compute this one:
- Before preceding to Modules, look over the examples. Then write a description of what
needs to be fixed in the ' Debugging ' section. Fix those things you find until the
troublesome cells work. Matson's Addage: It takes the same amount of time to debug the
code as it did to write it in the first place.
Modules
Watch out for this trap: You are forbidden to change the value of an
input parameter. That is this: mymod[ in1_, in2_] : = Module[ {stuff}, in2 = in1 * 2]
myanswer = mymod[ 3, 4]
is a really dumb module and it will give you an error. There are two
suggestions around this. First, and usually best is introducing a temporary variable
inside the module like this: mymod[ in1_] : = Module[ {stuff}, stuff = in1 * 2]
myanswer = mymod[ 4] which is a really inefficient way to multiply two
numbers, but gets the point across. The unfortunate thing about introducing an
intermediate variable is that it takes up memory which, in long calculations can be a
precious commodity. Only if you are using long arrays is it advisable to use the other
method.
The other method is to use a shared variable that is set outside the
module, not referenced therein (the variable name in this case must match throughout), but
changed inside: mymod[ in1_] : = Module[ {stuff}, results = in * 2]
results = 3;
myanswer = mymod[4]
which is an equally dumb module, but shows one way of getting around this forbidden
operation. This forbidding of changing the input parameters is actually a good thing. It
prevents you from doing unwanted and dangerous things by accident.
- Write a Do loop which create a windowed average of the list ' manof '. In this case, you
will replace the first element with the average of the 1st, 2nd, and 3rd. Then, the second
will be replaced by the average of the 2nd, 3rd, and 4th. Continue through the list until,
but leave the last two element alone. Be clever and don't make your windowed average
depend on the list ' manof '. If you are feeling like you have lottsa time, outside the Do
loop replace the last with the average of the last three, and I bet you can figure out
what to do with the second to last.
Under the "Create a scaling tool..." section create a module
that rescales an arbitrary list so it fits in the (arbitrary) range [ yourmin, yourmax].
Let's call it Scaler and when its called it should have the syntax: Scaler[ list, yourmin,
yourmax] and it will return a new list that is the newly scaled version of 'list'.
- Create a plot of the list ' tse ' (you did that above). Apply your rescale tool to ' tse
' to arrive at the list ' tsescaled ' . Use the new range [0,1]. Plot the rescaled tse to
show it matches, except the scale of course!
Please print out the notebook file once again and hand it in with any written comments
you've made.
Lesson 6: A Real Problem!
Remember the problem I mentioned last PS? Lets say we want to model waves impinging on
a slit (who's width is about the same as the wavelength of the waves). I would like you to
compute the intensity of waves at a point behind a single slit. One must compute a
2-D integral known as the propagation integral. It models how waves are diffract,
propagate to a new place, and interfere at the point of observation. If you wanted to plot
the intensity behind such a slit at many points along a plane parallel to that slit, you
would need to do a 2-D integral for every point (that you want to) on the plane. Later you
could make plot of the intensity everywhere behind the slit! And, you know, this sounds
like such a great example, I'm going to have you work on it. In this case, we'll make the
waves deBroglie matter waves!
Download the PS6 file(**not
operative**) . Its
mostly blank, however, I've included a cell to fetch a set of really handy functions in
the notebook ' useful.ma(**not
operative**)'. If you haven't downloaded it, do so now (you may have when doing PS5).
Don't forget to execute this cell before proceeding!
- The next cell contains a function which will act as a mask - imagine it to model a piece
of cardboard with a really small hole. In fact, we can visualize this really neatly by
using one of the special visualizations functions. After executing the second cell, create
a table of 2-D data from mask[x,y] allowing both the x and y ranges to go from [-10, 10]
in steps of 0.2. Don't let it print out (i.e., use the semicolon)!
- Now visualize it using: ListDensityPlot[ your2Dlist, Mesh->False, Frame->False,
PlotRange->Automatic]
- You should get into the habit of documenting your code. Insert messages (in the form of
smalltext or subsubsections) to help other understand what things are doing.
- The third cell contains some directives which prevent annoying warning message from
printing. We all agree that the computation we are about to do will be rather approximate,
we don't need to be reminded over and over again. Execute this cell.
Create a module which I'll call PropInt. It should have this syntax:
PropInt[ L, accuracy, x,y]. It needs to numerically compute the wave's field at
point (x, y) behind the mask (slit):
Instead of using the Integrate function, use Nintegrate; the parameter '
accuracy ' is used like this: Nintegrate[ expression , limits ,
AccuracyGoal->accuracy]
A word to the wise: Always include a ' Clear[ function ] ' command
before (and in the same cell as) any function or module definitions.
Try out your new module PropInt[ L, accuracy, x,y]. Here's a cute
trick to see how long it takes to execute. Assuming that you put numerical values in for
L, accuracy, x,y: StartTime=TimeElapsed["Start",0];
PropInt[Infinity, 1,5,3]
TimeElapsed["Stop", StartTime];
- Once you have it working, try changing one thing at a time to see how the time and final
value change. First try L (the limits of integration) which should be set at Infinity for
best accuracy. Then (with L at Infinity) change accuracy. The default is 20. You probably
need to say in the range [1,30] unless you want to really mess up your day. Comment on the
trade-offs of accuracy and speed.
- Now that you can compute the field at a single point (x,y), you need to make a large
array (a 2-D list) each point representing the field strength at many points (x, y) on the
plane behind the slit mask.
Write a module called ' getintensitybehind' that: 1) starts
the timer, like in the test of PropInt[...]. 2) Make a 2 -D table that fills in x and y
points both ranging [0, ' size ' ] in increments of ' grain '. I'll call this table '
behind '. 3) Stop the timer, 4) Compute the intensity from the field: Re[ behind
Conjugate[ behind] ].
getintensitybehind hould have this syntax: getintensitybehind[ L, accuracy, size,
grain]
DON'T try to execute getintensitybehind yet!
- Exactly, what do you think getintensitybehind will do? Write it down carefully. Where
will it calculate the intensity?
- Test getintensitybehind by executing: getintensitybehind[ Infinity, 1, 30, 30]
- If it is working, you are ready to try establishing the intensity behind the slit by
executing:
result = getintensitybehind[ Infinity, 1, 30, 30] I estimate this will take about 70
minutes. We should coordinate this step if you aren't running it on your computer.
- I hope you noticed getintensitybehind computes only points concentrated on 1/4 of the
plane behind the slit. The intensity pattern is symmetric. If we tried to compute the
whole plane, we'd still be here waited for the computation to finish. We used a trick! Of
course, one can't alway make use of symmetry, but if you can, do so! To fill in the rest
of the point on the plane and to plot the result, use the cell at the end of this
notebook.
Please print out the notebook file once again and hand it in with any written
comments you've made.