You are on page 1of 143

Physicist's Introduction to Mathematica

Physics 200 Physics 50 Lab Revised for V6.0


Fall Semester 2000 Spring Semester 2006 Summer 2007
Nicholas Wheeler John Boccio John Boccio
REED COLLEGE Swarthmore College Swarthmore College
V4.0 Revised for V5.0

TABLE OF CONTENTS

Within any given Mathematica notebook you can use the resources in the Find menu to locate keywords,
whether they occur in text or commands. Fifteen notebooks live within the MM V6 Lessons folder; the follow-
ing list of section titles is intended to guide you to the particular notebook most likely to contain the material of
immediate interest.
2 Lab Contents.nb

Lab 0

‡ Why Bother to Learn Mathematica?

‡ Getting Started…and Stopped

‡ Terminating a Running Calculation

‡ Notebooks

‡ Input Techniques & Tips

‡ Sources of Information & Help

‡ Three Primary Flavors of =

‡ Clear, Remove

Lab 1: Basic Graphics

Part A
‡ Simple Plotting

‡ Filled Plot

‡ Polar Plot

‡ List Plot

‡ Parametric Plot

‡ Some Remarks about Memory Management

Part B
Lab Contents.nb 3

Part B
‡ 3-Dimensional Plotting

‡ Combining Figures

Lab 2: Basic Graphics (Part 2)

Part A
‡ Implicit Plot

‡ Graphics Primitives

‡ Arrows

‡ Vector Fields

‡ Other Graphics Available as Standard Add-ons

‡ Composite Figures…Revisited

Part B
‡ Animation

‡ Exporting Mathematica Graphics to TeX

‡ Installing Standard Add-on Packages

‡ Some Miscellaneous Resources

Physical Constants

Conversion from One System of Units to Another

Calendar

Maps

‡ Audio

‡ Finding Things in Notebooks


4 Lab Contents.nb

Finding Things in Notebooks

Lab 3: Algebra, Trigonometry, Calculus

Part A
‡ Basics

‡ Finding the Roots of a Polynomial

‡ Graphical Representation of Complex-valued Functions

‡ Solving Systems of Simultaneous Equations

Application to Collision Theory

‡ Trigonometry

‡ Matrix Algebra

Part B
‡ Simple Definite/Indefinite Integrals

‡ Numerical Integration

‡ Functions Defined by Integrals

‡ Multiple Integrals

‡ Ordinary & Partial Differentiation

‡ Limits & Series

Lab 4: Ordinary Differential Equations

Part A


Lab Contents.nb 5

‡ Solving ODEs in Various Applied Settings

Exponential Population Growth

Logistic Model of Limited Population Growth

Harmonic Oscillator

Part B
Damped Harmonic Oscillator

Harmonically Forced Damped Harmonic Oscillator

Simple Pendulum

Part C
Damped Pendulum

Quantum Oscillator

Part D
Ballistics

Planetary Motion

Endpoint Conditions

Lab 5: Partial Differential Equations & Related Topics

Part A
‡ Techniques for Solving PDEs in Various Applied Settings

Waves on a String

Separation of Variables

Polar Separation of the Helmholtz Equation (Vibration of a Drumhead)


6 Lab Contents.nb

Polar Separation of the Helmholtz Equation (Vibration of a Drumhead)

Modes of an Annular Drum

Summary Remarks Concerning the Separation Method

Part B
‡ Curvilinear Coordinate Systems

‡ Total Derivatives, Differentials, Fractional Change

Application to Dimensional Analysis

Physical Units and Conversions…Revisited

Lab 6: Recursive Processes & Chaos; Fitting Curves to Data

Part A
‡ Background

‡ Basic Tools

‡ Wagon's Cobweb Plot

Logistic Map and the Onset of Chaos

Digression: How to Make a Binary List from Two Lists

‡ Wagon's Bifurcation Plot

‡ Coupled Nonlinear ODEs with Chaotic Solutions

Part B
‡ Fitting Curves to Data
Lab Contents.nb 7

Fitting Curves to Data

Preliminary Remarks

Curve-fitting Techniques


Physicist's Introduction to Mathematica
Physics 200 Physics 50 Lab Revised for V6.0
Fall Semester 2000 Spring Semester 2006 Summer 2007
Nicholas Wheeler John Boccio John Boccio
REED COLLEGE Swarthmore College Swarthmore College
V4.0 Revised for V5.0

Laboratory 0

Why Bother to Learn Mathematica?

Until a few years ago my own response to that question would have been "Why indeed? I became a physicist in
order to learn some things about how Nature works, not things about some proprietary software…described in a
book thicker and heavier than any of my physics books!" But the fact of the matter is that we probe Nature not
with our bare hands, but with tools~man-made contrivances, whether we call them principles, theorems,
analytical techniques or multi-channel analyzers. So the short answer is: Because Mathematica is a wonderful
new tool~sharper and more broadly useful than most others that spring to mind, and remarkably easy to use.

Mathematica, first released in June 1988, is a creation of Stephen Wolfram (born in 1959). It provides
an almost exhaustive compendium of mathematical data and information, and a computing engine of such
immeasurably broad potential that no one can claim mastery of all its parts…which is why The Mathematica
Book is so thick, and why so many excellent monographs treating this or that special area of application have
come into being. Let us therefore accept at the outset that our present objective must be a limited one~to gain a
working familiarity with the elementary first principles of Mathematica, and some rough sense of its potential.
Refined procedures we agree to reserve for the day when the work at hand requires that we move beyond the
basics, and lends urgency to the effort.

It will very soon become apparent to you that Mathematica is so powerful~and so easy to control~that
it opens a door to quick-and-easy mathematical experimentation that until now has stood shut even to the
greatest minds~a door to an entirely new and much more improvisatory way of thinking about and doing pure
& applied mathematics. You will find yourself in position to do things that formerly you would not even have
dreamed of doing (certainly not of doing casually, without a lot of labor-intensive special-purpose program-
ming), and that the formulation/testing of conjectures has come to occupy a central position in your mathemati-
cal life.

Getting Started…and Stopped


2 Laboratory 0.nb

Getting Started…and Stopped

I begin with a cautionary word: It is inevitable that you will from time to time (and especially in the beginning)
steer Mathematica off the road. Do not panic .... that is the way to learn how it works.
Mathematica comes in two large and semi-autonomous packages:
• the computing engine itself, called the "kernel" ;
• the "front end", which mediates the flow of information between you and the kernel (or perhaps several
kernels, running simultaneously on several computers). The front end manages screen display, graphics,
access to the Help Browser and much else, and can perform certain tasks independently of the kernel; it was
conceived and designed not by Wolfram himself, but by Theodore Gray.
I will proceed in the assumption that you are running Mathematica 6.0 on Mac OSX. Occasional small details
change if you are running Windows; I am unfamiliar with them, and will not attempt to describe them.
You already have the front end running (starting Mathematica does that). To turn on the kernel and (more to the
point) to establish communication between the front end and the kernel the traditional procedure is to type 2+2
and hit ENTER:
In[2]:= 2+2

During the interval the kernal was starting your input acquired an input number, and the output (when at
last it appeared) was assigned a corresponding output number.
To experience the often blinding speed of Mathematica, try

In[3]:= 1000 !

In[4]:= Expand@H1 + xL ^ 100D

That was fast. How fast?

In[5]:= % êê Timing

The {0.xxxxxx,…} informs us that the calculation kept the kernel busy for 0.xxxxxx seconds. Clearly %
recalled the last result. %% recalls the one before that and so on.
The long response to 1000! is cluttering up the notebook. So we Select then double click the "cell" contain-
ing that In/Out pair; the output disappears, and the cell marker acquires an arrow at its base. Select/double
click again and the output reappears. Do the same for the expansion of (1+x)^100.
During the interval when a command keeps the kernel occupied for several seconds, the title bar will indicate
what is happening. Try the command below and it should indicate Running… for awhile, then Rendering…-
Running…
In[7]:= Plot3D@Sin@2 p xD Cos@2 p yD, 8x, -1, 1<, 8y, -1, 1<, PlotPoints Ø 200D êê Timing

Notice that~fairly typically~it took longer to render than to run. Mathematica will not accept new commands
while running/rendering; it places new commands in a queue but does not execute them(do not bother), it colors
the right cell markers yellow~its distractedly polite way of saying "One thing at a time, please; I'm thinking."
Notice that V6 has Live 3D real time rotation.
Laboratory 0.nb 3

Notice that~fairly typically~it took longer to render than to run. Mathematica will not accept new commands
while running/rendering; it places new commands in a queue but does not execute them(do not bother), it colors
the right cell markers yellow~its distractedly polite way of saying "One thing at a time, please; I'm thinking."
Notice that V6 has Live 3D real time rotation.

‡ Terminating a running calculation


Not infrequently you will want, for one reason or another, to terminate a calculation. Maybe you've realized you
have asked Mathematica to do the wrong thing, or the calculation has run so long that you suspect (Mathemat-
ica returns no progress reports) something may be wrong with your command, or Mathematica reports back
that it has been caught up in an endless loop. In such cases the first thing to try is
Ì-. Simple abort: hold down Ì and press period…and wait.
Equivalently, you might select Abort Evaluation from the front end's Kernel menu.The kernel has to "back
up," so the wait is roughly proportional to how deep you were into the calculation, but eventually (after perhaps
several minutes) an Out[#]=Aborted should appear.
But Mathematica, once started, reveals a single-minded reluctance to quit, and after a long wait you may con-
clude that the simple technique just described is not going to work. Or perhaps you are simply tired of waiting.
Try
Ì-q Simple quit Mathematica: you will be asked if you want to Save your work,
then both the front end and the kernel will shut down, and you should Restart. If that is ineffective, try hitting
ÌıÂ Hard dump of the kernel. Save your work, Quit Mathematica, Restart.
Finally, you can force quit Mathematica…but will lose any unsaved open documents. It is in anticipation of
such an event (or other misfortune) that you should be careful to

Save your notebook at frequent intervals.


SUGGESTION: WRITE THOSE THREE TERMINATION METHODS DOWN ON A SLIP OF PAPER. For when you most need them
you will not be able to access this notebook where they are described!

Notebooks

Mathematica documents are called "notebooks," and wear the suffix .nb Open the File menu, select New
(alternatively: hit Ì-N), and you have created a new notebook. Use File > Save As… (alternatively: ˜Ì-S) to
name and save the notebook.
Notebooks can be rendered in various "styles"~designs intended for different uses. Mathematica is shipped
with 20 canned designs: open Format > Style Sheet to see the list. Try them, one after the other, to see what
they do to this text.

I usually work in Default Style, but for present purposes I have selected and require you to work in TutorialBook Style. This I do for
a reason: in other styles the In[#] signals are surpressed when a notebook is reopened, and I need for you to be able to see
those. I have made the page 9.5 inches wide (that allows room for several input paletttes on a 17 inch screen), and run at 125% or
150% magnification. If you set up similarly you will be reading text pretty much as I intended it.
4 Laboratory 0.nb

I usually work in Default Style, but for present purposes I have selected and require you to work in TutorialBook Style. This I do for
a reason: in other styles the In[#] signals are surpressed when a notebook is reopened, and I need for you to be able to see
those. I have made the page 9.5 inches wide (that allows room for several input paletttes on a 17 inch screen), and run at 125% or
150% magnification. If you set up similarly you will be reading text pretty much as I intended it.

Different canned styles come equipped with different sets of options~few in some cases, numerous in others.
Open Format and activate Show ToolBar. Go to Notepad Style and open the ToolBar menu: it shows only
four options. Now go to Textbook Style: it shows 29 options. It was (primarily for the reason just stated, but
also) to obtain a workable set of options that I elected to work in TutorialBook Style.
Under Format you find Edit Style Sheet… and someday you may have occasion to do just that. The Mathemat-
ica Book tells you how. But for the moment we have already in hand all the resources we will need. My gen-
eral advice:
• Mathematica is intolerant of typos~all capitalization, every brace and bracket, every bit of punctuation
must be exactly right~so work with magnification big enough that you can clearly distinguish . from ,
etc.
• Show the ToolBar; it is a great aid to the insertion of section titles, explanatory text, etc.
• Make the page large, yet small enough to leave room on the screen an input palette or two.
• When opening a closed notebook to resume work, start with something simple like the standard 2+2;
otherwise the front end may be unable to find and connect with the kernel.

Input techniques & tips

‡ Parentheses
Mathematica assigns distinct and non-interchangeable responsibilities to (), [] and {}. Those I will explain in a
moment. But first a

TIP : The correct way to type (stuff) is not ( then stuff then ) but
H L then the stepleft key ¨ then stuff

That way you will avoid both the danger of forgetting or misplacing the ), and will avoid also the distraction of
Mathematica's signal that it has detected an unclosed parenthetic. A similar remark pertains~for the same
reasons~when running TEXShop … and, indeed, to all computer programming work.

• Mathematica reserves ( ) to delimit expressions, as in (1+x)^n and (a+b)(c+d).


• Mathematica reserves [ ] to identify the arguments of functions, where the term "function" is (as will
emerge) very broadly construed; simple examples are f[x,y] and Sin[x].
Laboratory 0.nb 5

• Mathematica reserves [ ] to identify the arguments of functions, where the term "function" is (as will
emerge) very broadly construed; simple examples are f[x,y] and Sin[x].
• Mathematica reserves { } to identify lists, where again the term will be very broadly construed; thus
{2,3,5,7,11,13} is a list of primes, and {{a,b},{c,d}} is a list of lists (i.e., a matrix).

‡ Palettes
Versions 1 and 2 of Mathematica required one to communicate with the front end in a kind of one-dimensional
"telegraphic" code. For example, to evaluate Ÿ 0 x e-x dx one had to enter
¶ 3

In[8]:= Integrate@x Exp@-x ^ 3D, 8x, 0, Infinity<D

That, as you see, still works, and is the style still preferred by some people. It is~in simple contexts~often the
quickest way to go, but never pretty. For many commands the telegraphic style remains mandatory in Version
5; look, for example~picking one from a zillion~to the following command:
In[9]:= Plot@SinIntegral@xD, 8x, 0, 20<, PlotRange Ø AllD

But~beginning with Version 3 and continuing with Versions 4, 5 and 6 ~it has become possible to
enter many commands using a "two-dimensional" code that looks much like ordinary mathematical notation.
Returning to our recent example, to evaluate Ÿ 0 x e-x dx one would enter
¶ 3

‡ x‰

3
-x
In[10]:= „x
0

This is accomplished with the aid of a collection of "palettes." The standard collection serves most needs, but
can readily be expanded by the user who has specialized requirements.

In the Palettes menu you see several options:


Open Calculus. Close.

Open LinearAlgebra. Close.

Open MultiVariableCalculus. Close.

Open Plotting. Close.

Open AlgebraicManipulation. Close.

Open BasicMathInput. Close.

Open BasicTypesetting. Close.


Open SpecialCharacters. Close.

Open SlideShow. Close.

Open NotebookLauncher. Redundant with Format > Style Sheet. Close


Open AlgebraicManipulation. Close.

Open BasicMathInput. Close.


6 Laboratory 0.nb
Open BasicTypesetting. Close.

Open SpecialCharacters. Close.

Open SlideShow. Close.

Open NotebookLauncher. Redundant with Format > Style Sheet. Close


I have highlighted the palettes I find most useful. There is a large element of redundancy present in the design
of the standard palettes; for example, everything on the BasicMathInput palette can be found also on one or
another of the more specialized palettes.
Many palette buttons produce characters with one or more blank boxes. ⁄ÑÑ=Ñ † is a good example. Use Í to
advance from box to box, entering data as you go.
What distinguishes the É boxes from the Ñ boxes? Suppose, having written

REMARK: Here and henceforth I have grayed out statements in input style that are not actually intended to be entered as input.

6 ‰-a x

you decide you want to integrate that function. Select the expression, then hit the ŸÑ ‡ „ Ñ button; you get
Ñ

‡ 6‰
Ñ
-a x
„Ñ
Ñ

and can use the enter key to construct/execute

‡ 6‰

-a x
In[11]:= „x
0

Take a moment to examine the output. Mathematica is compusive about reporting the preconditions necessary for its reported
conclusions/evaluations to make sense. Note also the presence of the easy-to-miss 6 in front of the If. The correct evaluation is not
1/a but 6/a.

Look to another example: Select

a+x
1+ 1+
b

and hit ‡Ñ to create


2
a+x
1+ 1+
b

Notice that Mathematica has automatically supplied parentheses of the appropriate shape and size.

tion sin2 [x], neither does it require anything so cumbersome as Hsin@xDL2 .


Do the same with Sin[x] and you discover that, while Mathematica does not recognize the common construc-

The short answer to our initial question: É boxes wrap around selected objects, Ñ boxes do not. Now we under-
stand why Mathematica calls É the "SelectionPlaceholder," and Ñ the "Placeholder."
Laboratory 0.nb 7

The short answer to our initial question: É boxes wrap around selected objects, Ñ boxes do not. Now we under-
stand why Mathematica calls É the "SelectionPlaceholder," and Ñ the "Placeholder."

Palette buttons are a great aid to speed and legibility. But they require use of the mouse, and in some situations
their repetitive use can become tedious (though deft use of Cut/Copy/Paste often permits accelerated escape
from the tedium). It is useful to know that the action of palette buttons can often be achieved directly from the
keyboard. Open File > Palettes > CompleteCharacters, then open (say) Technical Symbols and Shapes and
Icons. Move the selection arrow around over the face of the palettes and watch the bottom of the window. You
will discover, for example, that
› can be produced by typing the TEX-like command \[Watch Icon]. (Here I had to introduce an artificial space;
delete it to see why!)
Ÿ can be produced by typing either Âmath or \[Mathematica Icon]. (Artificial space)
⁄ can be produced by typing \[Kernel Icon]. (Artificial space)
œ can be produced either by Â:-@ or by \[Freaked Smiley]. (Artificial space)
É can be produced either by Âspl or by \[Selection Placeholder]. (Artificial space)
Ñ can be produced either by Âpl or by \[Place holder]. (Artificial space)
‰ can be produced either by Âee or by \[Exponential E]. (Artificial space)

 can be produced either by Âii or by \[Imaginary I]. (Artificial space)


p can be produced either by Âp or by \[P i]. (Artificial space)
Etc. There is a limit to how many such commands one can remember, but the point is one does not need to
remember them: palette design automatically reminds one of their existence.
In addition to the lengthy list of "longform" commands \[Etc] and a shorter list of "shortform" commands
Âetc it is possible (on Macintosh) to enter some symbols with commands of the form ı-p (which pro-
duces p); use ı- and ı˜- to run through the keyboard and discover the possibilities~most of which are
uninteresting.

Sources of Information & Help

‡ Built-in Sources
Open Help >Browser… and after a few seconds you will discover that you have no need to lug The Mathemat-
ica Book around with you; the entire thing~page for page~is built into the design of the Help Browser. So
also is Standard Add-on Packages. And much else. All very carefully indexed (open Help > Master Index…),
and supplied with hyperlinks at all appropriate places. We will explore some of those resources in a moment.
But there exist other/quicker ways to obtain information which are frequently quite useful. Suppose, for exam-
ple, that we had computed
8 Laboratory 0.nb



xj
Hj + uLn
In[12]:=
j=0

and find ourselves wondering "What in the world is a 'LerchPhi function'?" We might enter

In[13]:= ? LerchPhi

We get more detailed information if we we click the >> or equivalently

In[15]:= Information@LerchPhiD

LerchPhi@z, s, aD gives the Lerch transcendent PhiHz, s, aL, etc.

But~backing up to our starting point~if in



xj
Hj + uLn
In[16]:=
j=0

we Select the output and then open Help > Find Selected Function… we are instantly presented with a
detailed description of the "Lerch transcendent" and of its relation to (among others) the Riemann zeta and
polylog functions.
Distinct from and complementary to Information is Options. We can ask Mathematica itself to describe
the difference:
In[17]:= ? Information

In[18]:= ? Options

Many things~graphics most notoriously~support lots of options. Suppose, for example, we perform

In[19]:= Plot@Sin@xD, 8x, 0, p<D

and then become curious about the options which were available to us; to discover those, we enter

In[20]:= Options@%D

Later we will give attention to what those various options mean, how they are used. To discover what that use
of % was all about, we enter
In[21]:= ?%

Try Information[%] and Options[%] to see what you (don't) get.


I make very frequent/casual use of ? and Options, and encourage you to develop the same habit.

‡ Your Own "My Tricks" Notebook


I mention finally an undocumentable resource which will in time become the most valuable of all. Experience is
problem-solving, in this sphere as in all others. When Mathematica has presented difficulties which you have
finally overcome (it will, and you will), take the time to record your success in a dedicated notebook. You will
then never again have to solve that particular problem, and can use your former success as a Copy/Paste tem-
plate. For your
Laboratory 0.nb 9


then
Mathematica power = Problems successfully solved
t=today

And don't be too proud to save also~perhaps in a separate notebook of "Stolen Tricks"~a record of the ideas
developed by others that seem to you interesting, or potentially useful. Quite a number of those will be encoun-
tered as we proceed.
Sometimes your "tricks" will consist of programs that run a dozen or more lines (Mathematica programs are
seldom very long; that heavy work was done by the designers of the software), but more often they will consist
of felicitous selections from among available options. The value of your Tricks Notebooks will be much
increased if you include explanatory text and references~easy if you open Format > Show ToolBar. Notice
also that you need not add to the end of your notebook: you can introduce new material interstitially, in confor-
mity with some organizational pattern, with categories labled with appropriate Section titles.
Use the resources of the Find menu to locate material in your notebooks. The task is made easier if you embel-
lish your notebooks with appropriate tag words and phrases.

Three Primary Flavors of =

Enter the following:

In[22]:= ? =

In[23]:= ? :=

In[24]:= ? ==

What, in plain words, do those statements mean?


In[25]:= ?=

Mathematica understands that when we write

In[26]:= a=2

we are assigning the meaning 2 to the symbol a. So we have


In[27]:= a+1

If we now write

In[28]:= a = Sin@xD

we have reassigned meaning to a:


In[29]:= 1 - a2

In[30]:= Simplify@%D
10 Laboratory 0.nb

In[31]:= Clear@aD

When we write

In[32]:= g = Plot@x Sin@xD, 8x, 0, 100<D

we have, in effect, asserted that g will be the name of the graph. Here is an instance of the use of that name:
In[33]:= Show@gD

A mnemonically better name in this instance might have been something like

In[34]:= firstgraph = Plot@x Sin@xD, 8x, 0, 100<D

In[35]:= Show@firstgraphD

It was to permit such practice that the designers of Mathematica interpret xy to be a compound symbol or
"name," and require use of some special device to signify "multiplication":
x y Here the ¯ signifies multiplication; alternatively, use

x*y or x×y where × is produced Â*Â. Notice, however, that one must write

x.y if x and y are matrices.


Conversely, spaces cannot be used in names.
It is permitted to make several assignments simultaneously. Try

BEWARE! You will get a "Possible spelling error" message. Ignore it.

In[36]:= p = Tom
q = Dick
r = Harry

Notice that a single input has produced three lines of output. Now, as a test, try

In[39]:= List@p, q, rD

In[40]:= Clear@p, q, rD

NOTE: Mathematica capitalizes the names of all functions and commands. To avoid confusion~and the distraction of such "possible
spelling error" messages~you should assign lower case names to all your own variables and functions. In the present instance we
might better have written tom, dick & harry.

‡ Delayed Assignment: Functional Definition


In[41]:= ? :=

Were we to write

In[42]:= f = x17

(thus giving the name f to the expression on the right) we would~for some limited purposes~be in position
to treat f as though it were a function; try
Laboratory 0.nb 11

(thus giving the name f to the expression on the right) we would~for some limited purposes~be in position
to treat f as though it were a function; try
In[43]:= ∂x f

In[44]:= ‡ f „x

Clear@f, xD H*Execute but do not for the moment worry about the point
of this command. Do notice the use of H* *L to bracket COMMENTS*L
In[45]:=

But we would not be in position to ask "What is the value assumed by f at x = 3 ?" Or to plot f(x) . Mathemat-
ica understands
In[46]:= f@x_D := x17

to signify that we intend to delay the assignment of specific value to x; in short, to look upon the preceding
command as a description of the functional structure we have assigned to f[x]. We are only now in position
to make commands such as the following:
In[47]:= f@3D

H*Look up List in the Master Index. Be sure to open "Further Examples"*L


In[48]:= List@f@1D, f@2D, f@3DD

In[49]:= ∂x I f@xD2 + xM

In[50]:= Plot@f@xD, 8x, 0, 1<, PlotRange Ø AllD

Note the use of the subscripted _ to identify the "independent variable" x; its purpose becomes clearer
when you look at
In[51]:= f@x_, y_D := u x3 + v y3 + w

where we have announced our intention to look upon x, y as a variables, and u, v, w as adjustable
constants/parameters. Try
In[52]:= ∂x f@x, yD

which is not at all surprising, and

In[53]:= ∂u f@x, yD

which is a little bit surprising: Mathematica has uncomplainingly differentiated with respect to a parameter.

Piece-wise functional definition:

Not infrequently we develop interest in functions with "piece-wise" definitions. Look to this example:

In[54]:= Clear@veeD
12 Laboratory 0.nb

vee@x_D := 1 ê; x < -1
vee@x_D := -x ê; -1 < x < 0
In[55]:=

vee@x_D := +x ê; 0 < x < 1


vee@x_D := 1 ê; 1 < x
H* ê; means "use this rule when…"*L

In[59]:= Plot@vee@xD, 8x, -2, 2<D

An important instance of such a function is the Heaviside UnitStep function, which is a built-in resource of
Mathematica:
In[60]:= ? UnitStep

Plot@UnitStep@xD, 8x, -2, 2<,


PlotStyle Ø 88RGBColor@1, .3, 0D, Thickness@0.01D<<, PlotRange Ø 80, 2<D
In[61]:=

‡ Equality
In[62]:= ? ==

When you intend "equals" in the familiar sense, Mathematica expects you to write ==. Here are some simple
examples:
In[63]:= 2+2ã3

In[64]:= 2+2ã4

SolveAf2 + f - 1 ã 0E
H*Equation defines what Mathematica calls the "GoldenRatio"*L
In[65]:=

In[66]:= N@GoldenRatioD H*Asks for the numerical value of GoldenRatio*L

In[67]:= N@GoldenRatio, 30D H*Asks for 30-place accuracy*L

In[68]:= Solve@82 x + 3 y ã 1, 3 x + 5 y ã 1<, 8x, y<D

In[69]:= DSolve@8y '@xD ã a y@xD, y@0D ã 1<, y@xD, xD

‡ Secondary Flavors of = , and of some of its Relatives


Constructions like
===

=!= H*negation of the preceding*L

<

>

<=
Laboratory 0.nb 13

>=

return True/False output, and are used mainly in Mathematica programming. The first asks whether the
expression on the left is structurally identical to the expression on the right
In[70]:= 3 x2 === ∂x x3

In[71]:= Sin@xD2 + Cos@xD2 === 1 H*identity, but not "structural identity"*L

The final pair ask § ? and ¥ ? respectively, but require the expressions on left and right to be numeric, not
symbolic : with the Schwarz inequality in mind, we ask

In[72]:= I42 + 62 + 82 M I52 + 72 + 92 M ¥ H4 µ 5 + 6 µ 7 + 8 µ 9L2

but when we ask the general instance of the same question

In[73]:= Ia1 2 + a2 2 + a3 2 M Ib1 2 + b2 2 + b3 2 M >= Ha1 b1 + a2 b2 + a3 b3 L2

Mathematica (because it has not been informed that we intend the a's and b's to be real) remains non-committal.

Clear, Remove

Open a new notebook, enter f[u] and discover that its recent definition is still in force. It lives in the kernel,
and so will travel with you from notebook to notebook until either you explicitly discard it or terminate this
work session; i.e., until either you Quit Mathematica or Clear the definition. Now close and discard your
nameless new notebook.
Suppose you had interest at this point in defining
1
In[74]:= distance@t_D := r + g t2
2

Check to see what you have created

In[75]:= distance@tD

and get something weird. That is because you have previously assigned meanings to r and g, and those are
still lively:
In[76]:= r

In[77]:= g

In[78]:= Show@gD

You might reassign meaning to those symbols, but how do you simply strip away those prior assignments, and
restore r and g to the list of "meaningless symbols"?
14 Laboratory 0.nb

In[79]:= ? Clear

Enter the command

In[80]:= Clear@r, gD H*Erases previous assignment*L

and check to confirm that the command did its work:

In[81]:= r

In[82]:= g

‡ Clearing functions
Mathematica's response to the query

In[83]:= ?f

reminds us that we have assigned the name f to two different functions…which we are not likely to confuse
(and neither is Mathematica), since one is a function of a single variable, and the other a function of two vari-
ables. Here's the rub: Mathematica affords no way to clear one without at the same time clearing the other (and,
indeed, clearing all things named f). Try it:
In[84]:= Clear@fD

In[85]:= ?f

In[86]:= Remove@fD

In[87]:= ?f

Mathematica has reported that it can now find no such placeholder. Notice that such reports are not numbered
"output," but have more the status of "announcements."

TIP: To preserve flexibility, always assign distinct names to distinct functions. In the preceding examples we
might better have written
In[88]:= f1@x_D := x17
f2@x_, y_D := u x3 + v y3 + w

TIP: One should be careful to clear assignments/definitions when you are finished with them. This frees up
memory, and helps avoid nasty surprises that can lead to crashes. But you will sometimes forget, so…

TIP: Make
ClearAthe letters ê strings you expect to assignE

your first command in every computation.


Laboratory 0.nb 15

your first command in every computation.

We will have no immediate need of the more comprehensive command

In[90]:= ? ClearAll

Save.
Physicist's Introduction to Mathematica
Physics 200 Physics 50 Lab Revised for V6.0
Fall Semester 2000 Spring Semester 2006 Summer 2007
Nicholas Wheeler John Boccio John Boccio
REED COLLEGE Swarthmore College Swarthmore College
V4.0 Revised for V5.0

Laboratory 1
Part A

Basic Graphics

Pen-&-ink mathematicians have traditionally found graphics so labor intensive that they have tended to avoid
figures whenever possible…and, when a figure could not be avoided, to make do with a merely qualitative
representation of the points at issue. Figures have tended to see service only as expository devices, used to
express what was already known, and seldom to be used as aids to discovery.
Mathematica makes the production of accurate figures~of many types~so quick and easy that it should/will
become your habit to look to the graphical aspects of problems before you have fully understood them. The
graphical aspects of your mathematical work will assume enlarged importance. Graphics~formerly an exposi-
tory device~has become an exploratory tool.

‡ Resources
Your principal resource is at your fingertips. Open Help > Find Selected Function > Visualization and
Graphics, then look around to see what I mean.
Basic graphics commands are simple and commonsensical, but you should be aware that if you go to File >
Palettes > Plotting you will find buttons that produce things like Plot[‡,{·,·,·}], and so remind you of
the required syntax, and help you to get all the brackets and punctuation just right (Mathematica is unforgiving
in those respects!).
Your favorite Mathematica text is certain to contain a long/detailed graphics section.
Keep a My Graphics notebook, recording your successful accomplishments; it is likely to become your primary
reference, especially with regard to the correct management of the numerous "options" which are the main
source of confusion in this area.
2 Laboratory 1A.nb

‡ Simple Plotting
In[2]:= ? Plot

First Example:

In[3]:= Plot@Tan@xD, 8x, 0, 20<D

Notice that Mathematica has no trouble at all with the infinities.


Notice also that the output consists not of the figure, but of the not-too-informative expression -Graphics-.
That output can be surpressed by appending a ; to our original command (try it). We will henceforth adopt that
practice.
We look now to a few basic elaborations of the preceding basic command:
In[4]:= Plot@Tan@xD, 8x, 0, 20<, Frame Ø TrueD

In[5]:= ? Frame

Plot@Tan@xD, 8x, 0, 20<, Frame Ø True,


FrameTicks Ø 8Range@0, 6 p, pD, Automatic, None, None<D
In[6]:=

In[7]:= ? FrameTicks

In[8]:= ? Range

Plot@Tan@xD, 8x, 0, 13 p ê 2<, Frame Ø True,


FrameTicks Ø 8Range@0, 6 p, pD, Automatic, None, None<,
In[9]:=

PlotStyle Ø 8AbsoluteThickness@2D<D

Plot@Tan@xD, 8x, 0, 13 p ê 2<, Frame Ø True,


FrameTicks Ø 8Range@0, 6 p, pD, Automatic, None, None<,
In[10]:=

PlotStyle Ø 8RGBColor@0.2, 0, 0.8D, Thickness@0.007D<D

In[11]:= ? RGBColor H*See the Color Charts, mentioned above*L

In[12]:= ? Thickness

In[13]:= ?? AbsoluteThickness

REMARK: "Absolute thickness" is measured in printer's points (multiples of about 1/72nd of an inch).

Second Example:

In[14]:= PlotASin@tD ‰-tê10 , 8t, 0, 20 p<E

Mathematica tries to show "the interesting part" of a figure, with the result that it has here clipped off some
detail. I give two ways to override that defect:
In[15]:= PlotASin@tD ‰-tê10 , 8t, 0, 20 p<, PlotRange Ø AllE
Laboratory 1A.nb 3

In[16]:= PlotASin@tD ‰-tê10 , 8t, 0, 20 p<, PlotRange Ø 8-1, 1<E

Third Example:

This example, borrowed provides a taste of "graphical discover/exploration."


Plot@Sin@xD + ArcSin@xD, 8x, -0.85, 0.85<, Frame -> True,
FrameTicks Ø 88-0.8, 0.8<, 8-1, 0, 1<, None, None<D
In[17]:=

The graph is remarkable for its unexpected linearity. To gain a sense of how linear it truly is, we might proceed
as follows:
In[18]:= Clear@aD

In[19]:= a = Sin@.5D + ArcSin@.5D

x H*Equation of straight line passing through a


a
In[20]:= linear@x_D :=

couple of selected points: the origin and the point H0.5,aL*L


.5

Plot@8Sin@xD + ArcSin@xD, linear@xD<, 8x, -0.85, 0.85<,


Frame -> True, FrameTicks Ø 88-0.8, 0.8<, 8-1, 0, 1<, None, None<D
In[21]:=

which reveals a slight departure from linearity at the ends. The mystery is explained when we enter

In[22]:= Series@Sin@xD + ArcSin@xD, 8x, 0, 15<D

and discover that the Maclaurin expansion has no terms of orders 2, 3, or 4. We made first use here of the
following resource:
In[23]:= ? Series

The dangling O@xD16 is an uninformative annoyance, but is easily avoided:


In[24]:= Series@Sin@xD + ArcSin@xD, 8x, 0, 7<D êê Normal

‡ FilledPlot
Consider the following function
1
In[25]:= sechsquared@x_D := Sech@xD2
2

has all the properties required of a probability distribution

‡ sechsquared@xD „ x

In[26]:=

‡ x sechsquared@xD „ x

In[27]:=

‡ x sechsquared@xD „ x

2
In[28]:=

and when plotted looks very Gaussian (or "normal"):


4 Laboratory 1A.nb

and when plotted looks very Gaussian (or "normal"):

In[29]:= Plot@sechsquared@xD, 8x, -4, 4<D

Direct visual comparison with the Gaussian with the same variance is enhanced if one makes use of a resource
provided as a Standard Add-On:

F
1 1 x 2
In[30]:= gaussian@x_, s_D := ExpB-
s 2p 2 s

F>, 8x, -4, 4<, Filling Ø 81 Ø 82<<F


p2
In[32]:= PlotB:sechsquared@xD, gaussianBx,
12

‡ Polar Plot
Not infrequently the result of physical calculation lends itself better to polar than to Cartesian graphical represen-
tation. For example, the theory of planetary motion (Kepler problem) leads to an equation of the form
constant
1 + eccentricity µ cos HqL
r=

The relevant software is provided as an add-on to Mathematica:

In[33]:= Needs@"BarCharts`"D; Needs@"Histograms`"D; Needs@"PieCharts`"D

In[34]:= ? PolarPlot

, 8q, 0, 2 p<F
1
In[35]:= PolarPlotB
1 + .8 Cos@qD

Slight adjustment causes the orbit to precess:

, 8q, 0, 20 p<F
1
In[36]:= PolarPlotB
1 + .8 Cos@1.01 qD

Try these further examples of polar plots:

In[37]:= PolarPlotA9t, t1.1 , t1.2 =, 8t, 0, 2 p<E

In[38]:= PolarPlot@Sin@5 qD, 8q, 0, 2 p<D

‡ List Plot
In[39]:= ? ListPlot

The familiar Fibonacci numbers are available as a built-in resource:

In[40]:= ? Fibonacci

In[41]:= Fibonacci@50D

Make a table of the first 10 Fibonacci numbers


Laboratory 1A.nb 5

In[42]:= fib = Table@Fibonacci@nD, 8n, 10<D

and use ListPlot to display that data graphically:


In[43]:= ListPlot@fib, GridLines Ø Automatic, Prolog Ø AbsolutePointSize@5DD

Note the techniques used to turn on the grid lines, and to adjust the point size.

‡ Parametric Plot
In[44]:= ? ParametricPlot

First Example: Simple Cycloid

A circle of unit radius rolls along the x-axis. We are interest in the curve traced by a point P marked on the
circumference of the circle. Working from a sketch, we are led to define
In[45]:= x@q_D := q - Sin@qD
y@q_D := 1 - Cos@qD

In[47]:= ParametricPlot@8x@qD, y@qD<, 8q, 0, 6 p<D

The figure is misleading because different scales are used on the two axes; we now correct that defect, place the
frame ticks at more natural places, and highlight the curve itself:
ParametricPlot@8x@qD, y@qD<, 8q, 0, 4 p<, AspectRatio Ø Automatic,
Frame Ø True, FrameTicks Ø 880, 2 p, 4 p<, 80, 1, 2<, None, None<,
In[48]:=

PlotStyle Ø 8RGBColor@0, 0, 1D, Thickness@0.007D< D

NOTE: Sometimes Mathematica produces a figure that is unaccountably tiny. In such cases, click on the figure and drag the handles
(now visible) to rescale the figure.

"Hypocycloids" and "hypercycloids" result when the point P is placed interior/exterior to the unit circle. Here
we make the appropriate modifications:
In[49]:= Clear@rD

In[50]:= x@q_, r_D := q - r Sin@qD


y@q_, r_D := 1 - r Cos@qD

8x@q, 1.0D, y@q, 1.0D<, 8x@q, 1.5D, y@q, 1.5D<<, 8q, 0, 4 p<,
In[52]:= ParametricPlot@88x@q, 0.5D, y@q, 0.5D<,

AspectRatio Ø Automatic, Frame Ø True,


FrameTicks Ø 880, 2 p, 4 p<, 80, 1, 2<, None, None<,
PlotStyle Ø 8RGBColor@1, 0, 0D, 8<, RGBColor@0, 0, 1D<D

Second Example: Epicycles

A wheel of given radius turns with given angular velocity. Pinned at its circumference is a second wheel of
given radius that turns with given angular velocity. And pinned to its circumference is a third wheel. Etc. We
are interested in the motion of a point marked on the circircircumference of the last wheel.
6 Laboratory 1A.nb

In[53]:= ParametricPlotBEvaluateB

8Cos@qD, Sin@qD< + 8Cos@7 qD, Sin@7 qD< + :CosB-17 q + F, SinB-17 q + F>F,


1 1 p p
2 3 2 2
8q, 0, 2 p<, AspectRatio Ø Automatic, Frame Ø TrueF

Adjustment of the numerics would, of course, result in different curves. It is not immediately obvious why the
present numerics (1, 7 & |17) generate 6-fold symmetry.
Note the use here of

In[54]:= ? Evaluate

without which the argument of ParametricPlot[]would not be a list {,}, as it is required to be.

Third Example: Lissajous Figures

The following construction is familiar to anyone who has ever played with an oscilloscope:

In[55]:= Clear@a, b, x, yD

In[56]:= x@t_, a_, a_D := a Cos@a tD


y@t_, b_, b_, d_D := b Cos@b t + dD

ParametricPlot@8x@t, 2, 2D, y@t, 1, 3.00, p ê 2D<,


8t, 0, 16 p<, AspectRatio Ø AutomaticD
In[58]:=

ParametricPlot@8x@t, 2, 2D, y@t, 1, 3.01, p ê 2D<,


8t, 0, 16 p<, AspectRatio Ø AutomaticD
In[59]:=

Fourth Example: Cornu Spiral

The Cornu integrals arise in physical optics (diffraction theory). The following pretty figure involves some
pretty heavy calculation; we'll ask Mathematica how long it takes.

cornu@t_D := :‡ SinAu2 E „ u, ‡ CosAu2 E „ u>


t t
In[60]:=
0 0

ParametricPlot@Evaluate@cornu@tDD, 8t, -10, 10<,


AspectRatio Ø AutomaticD êê Timing
In[61]:=

Now Save, Quit, and in a freshly opened Mathematica proceed to Part B.


Physicist's Introduction to Mathematica
Laboratory 1
Part B

‡ 3-Dimensional Plotting
In[2]:= ? Plot3D

The basic command is very simple:

In[3]:= Clear@fD

f@x_, y_D := Ix2 + 3 y2 M ‰1-x


2 -y2
In[4]:=

In[5]:= Plot3D@f@x, yD, 8x, -2, 2<, 8y, -3, 3<D

Here we exercise a few of the available options:


Plot3D@f@x, yD, 8x, -2, 2<, 8y, -3, 3<,
BoxRatios Ø 84, 5, 3<,
In[6]:=

PlotPoints Ø 30,
AxesLabel Ø 8"x", "y", None<D

Use ? to see what Mathematica has to say about those options. To better position the ticks and labels we use
In[7]:= ? AxesEdge

doublehump = Plot3D@f@x, yD, 8x, -2, 2<, 8y, -3, 3<,


BoxRatios Ø 84, 5, 3<,
In[8]:=

PlotPoints Ø 30,
AxesLabel Ø 8"x", "y", None<,
AxesEdge Ø 8Automatic, 81, -1<, 81, 1<<D

It is easy to adjust the viewpoint

In[9]:= ? ViewPoint

In[10]:= Show@doublehump, ViewPoint Ø 81.6, 0, 0.7<, Boxed Ø False, Axes Ø NoneD

In[11]:= Show@doublehump, Boxed Ø False, Axes Ø None, ColorFunction Ø HWhite &LD

One can also tinker with the colors, the source of illumination, etc. The literature supplies examples.

Save.

RevolutionPlot3D and SphericalPlot3D are 3-dimensional analogs of PolarPlot, and like the latter are
available as add-ons:
2 Laboratory 1B.nb

In[13]:= ? RevolutionPlot3D

In[14]:= RevolutionPlot3D@q, 8r, 0, 3<, 8q, 0, 2 p<D

RevolutionPlot3DAr2 , 8r, 0, 3<, 8q, 0, 2 p<, Boxed Ø False,


Axes Ø False, PlotPoints Ø 40, BoxRatios Ø 81, 1, 2<E
In[15]:=

In[16]:= SphericalPlot3D@2, 8f, 0, p<, 8q, 0, p<D

SphericalPlot3DBq, 8f, 0, p<, :q, 0, >,


7p
In[17]:=
2
Boxed Ø False,
Axes Ø False,
PlotPoints Ø 60F êê Timing

Save.

A Physical Example: Larmor Radiation

The directional dependence of the radiation emitted by an accelerated charge is (in non-relativistic approxima-
tion) given by Joseph Larmor's "sine squared" law (see Griffiths, Introduction to Electrodynamics §9.2.3). First
we plot the distribution

In[18]:= larmor = SphericalPlot3DASin@fD2 , 8f, 0, p<, 8q, 0, p<,


Boxed Ø False,
Axes Ø False,
PlotPoints Ø 40E

Then we construct a line indicating the direction in which the charged particle has been assumed to be
accelerating
acceleration = Graphics3D@8AbsoluteThickness@2D,
RGBColor@1, 0, 0D, Line@880, 0, 0<, 80, 0, 2<<D<, Boxed Ø False D
In[19]:=

In[20]:= Show@accelerationD

And finally we superimpose the two figures:

In[21]:= Show@8larmor, acceleration<D

Save.

I have never had physical need of the following resource


In[22]:= ? ListPlot3D

and pass it over in silence. You can imagine what it does, and how it works.
Laboratory 1B.nb 3

and pass it over in silence. You can imagine what it does, and how it works.

The following resource is, on the other hand, often indispensible

In[23]:= ? ParametricPlot3D

Parameterized Space Curve

We start with a parameterized space curve, such as might arise from solution of equations of motion:

>, 8t, 0, 10<,


t t -
t

In[24]:= ParametricPlot3DB: Sin@10 tD, Cos@10 tD, t ‰ 10

10 10
PlotPoints Ø 400F

Sphere

It takes two parameters to identify the points on a surface; here we use co-latitude q and longitude f to parame-
terize the points on the surface of a sphere:
In[25]:= x@f_, q_D := Sin@qD Cos@fD
y@f_, q_D := Sin@qD Sin@fD
z@f_, q_D := Cos@qD

In[28]:= ParametricPlot3DB8x@f, qD, y@f, qD, z@f, qD<,

:f, 0, >, :q, >,


3p p 19 p
,
2 20 20
Boxed Ø False, Axes Ø NoneF

Torus

Here is a variant of the same basic idea:

In[29]:= F@u_, v_D := 8Cos@uD H2 + Cos@vDL, Sin@uD H2 + Cos@vDL, Sin@vD<

In[30]:= ParametricPlot3DBEvaluate@F@u, vDD,

:u, - p>, 8v, 0, 2 p<, Boxed Ø False, Axes Ø NoneF


1 3
p,
6 2

Save.

Two-dimensional display of 3D data~in the style of a topographic map~is often quite informative. Mathemat-
ica affords two complementary alternatives:
In[31]:= ? ContourPlot

and its low-resolution (and generally less interesting) cousin, DensityPlot (see below):
4 Laboratory 1B.nb

and its low-resolution (and generally less interesting) cousin, DensityPlot (see below):

Example: Eigenstates of a Quantum Particle in a Triangular Box

In some recent work ("2-dimensional 'particle-in-a-box' problems in quantum mechanics" (1997)) I studied the
quantum mechanics of a particle confined to the interior of a polygonal box, for boxes of various favorable
shapes. The 45-45-90 box led to eigenfunctions of a form which I first describe and then plot:
In[32]:= Clear@m, n, x, yD

In[33]:= boxfunction@x_, y_, m_, n_D := Sin@m p xD Sin@n p yD - Sin@n p xD Sin@m p yD

groundstate =
ContourPlot@boxfunction@x, y, 1, 2D, 8x, -1, 1<, 8y, -1, 1<, PlotPoints Ø 100D
In[34]:=

excitedstate =
ContourPlot@boxfunction@x, y, 2, 3D, 8x, -1, 1<, 8y, -1, 1<, PlotPoints Ø 100D
In[35]:=

I found that clarity was sometimes served (though some information lost) if I turned off the shading:
ContourPlot@boxfunction@x, y, 2, 3D, 8x, -1, 1<,
8y, -1, 1<, PlotPoints Ø 100, ContourShading Ø FalseD
In[36]:=

Comparison of the two preceding figures exposes this point: the contours should not be confused with nodal
curves; they are "equi-value contours," not "null-value contours." Next we look to a more highly excited state:
ContourPlot@boxfunction@x, y, 11, 15D, 8x, -1, 1<,
8y, -1, 1<, PlotPoints Ø 100, ContourShading Ø FalseD
In[37]:=

Drag to size to get a better view.

Similar devices might/will be used to represent the vibration of a drum head (triangular membrane).

Save.

Example~Revisited

We previously used Plot3D to display the function


In[38]:= f@x, yD

Now we use ContourPlot to display the same information:


In[39]:= ContourPlot@f@x, yD, 8x, -2, 2<, 8y, -3, 3<,
PlotPoints Ø 50,
ColorFunction Ø HHue@1 - Ò ê 2D &LD

REMARK: You don't~at least initially~have to understand such details to use them, and some experimentation will often teach
you how they work. It is in that spirit that we next revisit our recent wavefunction:
Laboratory 1B.nb 5

REMARK: You don't~at least initially~have to understand such details to use them, and some experimentation will often teach
you how they work. It is in that spirit that we next revisit our recent wavefunction:

In[40]:= ContourPlot@boxfunction@x, y, 2, 3D, 8x, -1, 1<, 8y, -1, 1<,


PlotPoints Ø 100,
ColorFunction Ø HHue@1 - Ò ê 2D &LD

Look now, by way of comparison, to the DensityPlot of the function:


In[41]:= ? DensityPlot

In[42]:= DensityPlot@f@x, yD, 8x, -2, 2<, 8y, -3, 3<,


PlotPoints Ø 50D

I have never encountered a situation in which the DensityPlot was the interesting way to go.

Save.

We now use ContourPlot to distinguish two levels of the function:

In[43]:= ContourPlot@f@x, yD, 8x, -2, 2<, 8y, -3, 3<,


PlotPoints Ø 100,
FrameTicks Ø 8Range@-2, 2D, Range@-3, 3D, None, None<,
ContourShading Ø False,
Contours Ø 81, 0.5<,
ContourStyle Ø 88Thickness@0.015D<, 8Thickness@0.0005D<<D

‡ Combining Figures
Suppose~having produced a set of figures

In[44]:= ? BesselJ

= Plot@BesselJ@0, 8x,
8x,
In[45]:= g0 xD, 0, 20<D
= Plot@BesselJ@1,
8x,
g1 xD, 0, 20<D
= Plot@BesselJ@2,
8x,
g2 xD, 0, 20<D
g3 = Plot@BesselJ@3, xD, 0, 20<D

you decide to superimpose them. There are two ways to proceed. First, you might use

In[49]:= ? Show

to produce
In[50]:= Show@g0, g1, g2, g3D

Note that the original figures were drawn with different magnifications (reckoned by Mathematica to be opti-
mal in each individual case), and displayed different sets of numbers on the y-axis; Mathematica took all of that
into account when it constructed its unified merger. Alternatively, you might have commanded
6 Laboratory 1B.nb

In[51]:= Plot@8
BesselJ@0, xD,
BesselJ@1, xD,

xD<, 8x, 0, 20<D


BesselJ@2, xD,
BesselJ@3,

to recreate the same effect.


You might, on the other hand, find it more instructive to juxtapose the figures. That is accomplished with

In[52]:= ? GraphicsRow

Try it:

In[53]:= GraphicsRow@8g0, g1, g2<D

To see the graphic that lives now in Mathematica's mind you must command
In[54]:= Show@%D

Drag to size.

More attractive results are achieved if we redraw the figures in a way which forces a higher degree of standard-
ization:
b0 = Plot@BesselJ@0, xD, 8x, 0, 20<,
PlotRange Ø 8-0.5, 1<, Ticks Ø 8Automatic, 81<<D
In[59]:=

b1 = Plot@BesselJ@1, xD, 8x, 0, 20<, PlotRange Ø 8-0.5, 1<,


Ticks Ø 8Automatic, 81<<D
b2 = Plot@BesselJ@2, xD, 8x, 0, 20<, PlotRange Ø 8-0.5, 1<,
Ticks Ø 8Automatic, 81<<D
b3 = Plot@BesselJ@3, xD, 8x, 0, 20<, PlotRange Ø 8-0.5, 1<,
Ticks Ø 8Automatic, 81<<D

In[63]:= Show@GraphicsRow@8b0, b1, b2<DD

Drag to size.

Here is a different arrangement:

In[64]:= Show@GraphicsGrid@88b0, b1<, 8b2, b3<<DD

Drag to size.

Save.
Physicist's Introduction to Mathematica
Physics 200 Physics 50 Lab Revised for V6.0
Fall Semester 2000 Spring Semester 2006 Summer 2007
Nicholas Wheeler John Boccio John Boccio
REED COLLEGE Swarthmore College Swarthmore College
V4.0 Revised for V5.0

Laboratory 2
Part A

Basic Graphics (Part 2)

We resume this survey where we left off in Lab 1.

‡ Implicit Plot
To describe/draw a unit circle you might proceed

In[2]:= y@x_D := 1 - x2

In[3]:= Plot@y@xD, 8x, -1, 1<D

but you only got half the intended figure, and it is missshapen; tweaking is required:

In[4]:= Plot@8y@xD, -y@xD<, 8x, -1, 1<, AspectRatio Ø AutomaticD

Alternatively, you might proceed

In[5]:= x@q_D := Cos@qD


y@q_D := Sin@qD

ParametricPlot@8x@qD, y@qD<, 8q, 0, 2 p<, AspectRatio Ø AutomaticD


H*Try this also with the option omitted*L
In[7]:=

But it would be most natural to proceed (in the spirit of Descartes himself) from x2 + y2 = 1. This can be accom-
plished as follows:
In[10]:= Clear@x, yD
2 Laboratory 2A.nb

More Interesting Example

In[13]:= ContourPlotACosAx2 E ã SinAy2 E, 8x, -2 p, 2 p<, 8y, -2 p, 2 p<E

Better, but too coarse-grained to be very informative. Try

In[14]:= ContourPlotACosAx2 E ã SinAy2 E, 8x, -2 p, 2 p<, 8y, -2 p, 2 p<, PlotPoints Ø 300E

Much better. But took awhile, and made fairly heavy demands upon the kernel's memory.

Save

‡ Graphics Primitives
Graphics are constructed by assembly of points, lines and similar "primitives". Here follow the basic descrip-
tions of some of the most essential primitive elements
In[15]:= ? Point

In[16]:= ? Line

In[17]:= ? Rectangle

In[18]:= ? Circle

In[19]:= ? Disk

In[20]:= ? Text

The basic command is Show[Graphics[{list of primitives}]]. Primitives may be individually "decorated"


with options, the construction in each instance being {option,option,…,primitive}. The following command
illustrates those principles:

8PointSize@0.05D, Point@8.5, .5<D<,


In[21]:= Show@Graphics@8

8PointSize@0.1D, Point@81, 1.5<D<,


8RGBColor@0, 0, 1D, PointSize@0.15D, Point@81.2, -.5<D<,

8GrayLevel@0.5D, Disk@8-.5, .75<, .75D<,


Circle@80, 0<, 1D,

8RGBColor@1, 0, 0D, Rectangle@8-.25, -.25<, 82, .25<D<,


88RGBColor@0, 1, 0D, Rectangle@81.6, -.6<, 81.7, 1.25<D<,
Text@"A Design After Mondrian", 81.7, -1<D<
<D,
PlotRange Ø All,
AspectRatio Ø AutomaticD

Notice that items entered late in the list overwrite (i.e., are "stacked on top of") earlier items.

‡ Arrows
Laboratory 2A.nb 3

Arrows
Arrows are primitive objects:

In[25]:= Graphics@8Arrow@880, 0<, 81, 1<<D<D

Note that the placement of the options in the following commands:

In[26]:= GraphicsB:ArrowheadsB::0.1, 1, >>F, Arrow@880, 0<, 81, 1<<D>F

In[27]:= Graphics@8RGBColor@1, 0, 0D, Arrow@880, 0<, 81, 1<<D<D

The basic command is Arrow[coordinates of tail,coordinates of head,option ,option,…], and by exercise of


the options one can control the design of each arrow.
We turn now to an important graphics resource in which Mathematica draws its own arrows:

Save again.

‡ Vector Fields
As physicists, we spend a lot of time thinking about "vector fields" of various sorts (they might be force fields,
or might refer to some kind of "flow," etc.)…but we seldom attempt to draw pictures of such objects. Mathemat-
ica takes the pain out of that exercise, and the results are often quite informative.
In[28]:= Needs@"VectorFieldPlots`"D

The basic resource is described/illustrated below

In[29]:= ? PlotVectorField

In[30]:= Options@PlotVectorFieldD

vectorfield@x_, y_D := 9x4 + y4 - 6 x2 y2 - 1, 4 x y3 - 4 x3 y=


H*vector field as a list of its component functions*L
In[31]:=

In[32]:= VectorFieldPlots`VectorFieldPlot@vectorfield@x, yD, 8x, 0, 3<, 8y, 0, 3<D

Open Help > Find Selected Function... > Add-ons…[Go To] PlotField and discover that the preceding
command has some close relatives
In[33]:= ? PlotGradientField

In[34]:= ? PlotHamiltonianField

Suppose we take the function (which we plotted in various ways in Lab 1) to be the description of (the negative
of) a potential

wagonspotential@x_, y_D := Ix2 + 3 y2 M ‰1-x


2 -y2
In[35]:=


4 Laboratory 2A.nb

forcefield = HNeeds@"VectorFieldPlots`"D;
VectorFieldPlots`GradientFieldPlot@-wagonspotential@x, yD, 8x, -2, 2<,
In[36]:=

8y, -2.5`, 2.5`<, PlotPoints Ø 20, BaseStyle Ø 8RGBColor@0, 0, 1D<DL

It would be interesting to compare the force field with the associated population of equipotentials; to that end
we construct
equipotentials =
ContourPlot@-wagonspotential@x, yD, 8x, -2, 2<, 8y, -2.5, 2.5<,
In[37]:=

PlotPoints Ø 50,
FrameTicks Ø FalseD

H*If the arguments are listed in the reverse order


In[38]:= Show@ equipotentials, forcefieldD;

then the shading masks some of the arrows. Try it.*L

As expected, the implied "lines of force" thread normally through the equipotentials. The color got lost when
the figures were combined, and I don't know how to fix that. Any ideas?

A More Interesting Example: Electric Dipole

In[39]:= Clear@equipotentials, forcefieldD

1 1
dipolepotential@x_, y_D := -
.1 + x2 + Hy - 1L2 .1 + x2 + Hy + 1L2
In[40]:=

REMARK: The blue terms were introduced to kill the singularities, which were found to mess up the display of the resulting force field.

In[41]:= equipotentials = ContourPlot@dipolepotential@x, yD, 8x, -4, 4<, 8y, -6, 6<,
PlotPoints Ø 50,
FrameTicks Ø False,
AspectRatio Ø AutomaticD

In[42]:= dipolefield = HNeeds@"VectorFieldPlots`"D;

8x, -4, 4<, 8y, -6, 6<, PlotPoints Ø 20, AspectRatio Ø AutomaticDL
VectorFieldPlots`GradientFieldPlot@-dipolepotential@x, yD,

In[43]:= Show@equipotentials, dipolefieldD;

The preceding constructions are also possible in 3D.


In[44]:= Needs@"VectorFieldPlots`"D

An Example

In[48]:= scalarfield@x_, y_, z_D := x2 y - z


Laboratory 2A.nb 5

field = HNeeds@"VectorFieldPlots`"D; VectorFieldPlots`GradientFieldPlot3D@


scalarfield@x, y, zD, 8x, 0, 1<, 8y, 0, 1<, 8z, 0, 1<, PlotPoints Ø 5DL
In[49]:=

In 3D the vectorheads are (by default) omitted, since they tend to clutter the figure. But they can be installed if
wanted:
In[50]:= HNeeds@"VectorFieldPlots`"D;

8x, 0, 1<, 8y, 0, 1<, 8z, 0, 1<, PlotPoints Ø 5, VectorHeads Ø TrueDL


VectorFieldPlots`GradientFieldPlot3D@scalarfield@x, y, zD,

We can~as in 2D~construct surfaces on which the scalar field is constant

In[53]:= Options@ContourPlot3DD

surfaces = ContourPlot3D@scalarfield@x, y, zD, 8x, 0, 1<, 8y, 0, 1<, 8z, 0, 1<,


Contours Ø 8scalarfield@0.5, 0.5, 0.2D, scalarfield@0.5, 0.5, 0.8D<,
In[54]:=

PlotPoints Ø AutomaticD

and we can superimpose those upon the figure that represents the gradient of the scalar field:

In[55]:= Show@field, surfacesD;

Save

‡ Other Graphics Available as Standard Add-ons


Open Help > Find Selected Functions... > Add-ons > Standard Packages > Graphics and you will see that
graphics of types we have not discussed are at your fingertips. You will easily discover how to work those
from the information/examples provided. I take explicit note of just a couple:
In[56]:= Needs@"PolyhedronOperations`"D

In[57]:= Show@PolyhedronData@"Octahedron"DD

In[58]:= Show@Stellate@PolyhedronData@"Octahedron"D, 4.DD

The next example takes a bit longer; be patient:

In[59]:= Show@Geodesate@PolyhedronData@"Dodecahedron"D, 3DD

In[60]:= Show@Truncate@PolyhedronData@"Icosahedron"D, 0.5DD

H*The @D tells Mathematica to assign default values to four adjustable


In[63]:= Show@Graphics3D@Torus@DDD

parameters that control two radii and the mesh, as explained below.*L

In[65]:= ? Torus

In[66]:= Show@Graphics3D@MoebiusStrip@2, 1, 80DDD

In[67]:= ? MoebiusStrip
6 Laboratory 2A.nb

In[68]:= Show@Graphics3D@DoubleHelix@1, 3, 4, 30DDD

‡ Composite Figures…Revisited
Sometimes one wants to display related figures with one superimposed upon the other (this we have several
times already done) or in organized array. I wrote these seven Mathematica lab manuals more or less simultane-
ously; so it came about that when I treated this subject in Laboratory 1 I had forgotten that I had already dis-
cussed the subject here. The following short discussion will therefore be redundant with what you have already
seen, but it does expose a few new points, and takes just a minute…so I keep it.
We begin by introducing a population of functions of importance in connection with the quantum oscillator:

In[69]:= He@n_, x_D := 1 ì 2n HermiteHBn, x í 2F

Y@n_, x_D := 1 ì
1
- x2
In[70]:= n! 2p ‰ 4 He@n, xD

From such evidence as this

‡ Y@0, xD Y@0, xD „ x

In[71]:=

‡ Y@1, xD Y@1, xD „ x

In[72]:=

‡ Y@0, xD Y@1, xD „ x

In[73]:=

we infer that the Y-functions are orthonormal.

In[74]:= state1 = Plot@Y@0, xD, 8x, -10, 10<, PlotRange Ø 8-0.7, 0.7<D

In[75]:= state2 = Plot@Y@1, xD, 8x, -10, 10<, PlotRange Ø 8-0.7, 0.7<D

In[76]:= state3 = Plot@Y@2, xD, 8x, -10, 10<, PlotRange Ø 8-0.7, 0.7<D

In[77]:= state4 = Plot@Y@3, xD, 8x, -10, 10<, PlotRange Ø 8-0.7, 0.7<D

In[78]:= state5 = Plot@Y@4, xD, 8x, -10, 10<, PlotRange Ø 8-0.7, 0.7<D

In[79]:= state6 = Plot@Y@5, xD, 8x, -10, 10<, PlotRange Ø 8-0.7, 0.7<D

We already know how to superimpose figures:

In[80]:= Show@state1, state2, state3D

Here we assemble them into an array:


statesarray =
Show@GraphicsGrid@88state1, state2<, 8state3, state4<, 8state5, state6<<DD
In[81]:=

In[82]:= Show@statesarray, Frame Ø True, FrameTicks Ø NoneD

The ticks clutter up the figure; we turn them off "after the fact" as it were:
Laboratory 2A.nb 7

The ticks clutter up the figure; we turn them off "after the fact" as it were:

In[83]:= Show@statesarray ê. HTicks Ø AutomaticL Ø HTicks Ø NoneLD

Here is a different arrangement of the same graphical data:


altstatesarray =
Show@GraphicsGrid@88state1, state2, state3<, 8state4, state5, state6<<D,
In[84]:=

Frame Ø True, FrameTicks Ø NoneD

It is now even more urgent that we turn off the ticks:

In[85]:= Show@altstatesarray ê. HTicks Ø AutomaticL Ø HTicks Ø NoneLD

Click on figure, grab handle and drag to desired size.


Physicist's Introduction to Mathematica
Laboratory 2
Part B

‡ Animation
The following animation shows how superimposed oscillator eigenstates contrive to mimic the sloshing charac-
teristic of classical oscillators. First we recall some definitions

In[2]:= He@n_, x_D := 1 ì 2n HermiteHBn, x í 2F

Y@n_, x_D := 1 ì
1
- x2
In[3]:= n! 2p ‰ 4 He@n, xD

and with the aid of those create a "table of figures":

H2 pL nF +
1 1 1
In[4]:= AnimateBPlotB Y@2, xD2 + Y@2, xD Y@3, xD CosB Y@3, xD2 ,
2 20 2
8x, -10, 10<, PlotRange Ø 80, 0.5<, Ticks Ø NoneF, 8n, 0, 19<F

Note the control buttons that have appeared in the window; they work just like a VCR.

Watch the movie, then delete the film strip and Save.

The following movie refers to the classical limit of that same familiar physics:

In[5]:= AnimateBShowBGraphicsB:

:RGBColor@0, 0, 1D, DiskB:2 + CosB nF, 0>, .1F>, H*mass point*L


2p

8GrayLevel@0.7D, Rectangle@8-.1, -.5<, 80, .5<D<, H*left wall*L


30

8GrayLevel@0.7D, Rectangle@84, -.5<, 84.1, .5<D<, H*right wall*L

:RGBColor@1, 0, 0D, RectangleB:0, -.02 + .01 CosB


2p
nF>,
30

:1.9 + CosB
2p 2p
nF, .02 - .01 CosB nF>F>H*rubber band*L
30 30
>F, AspectRatio Ø AutomaticF, 8n, 0, 29<F

Note that (and how) the rubber band has been designed to get thicker as it gets shorter. The right wall was
included as a way of forcing all frames to be drawn to the same scale; otherwise Mathematica would draw each
to its own scale~the scale that Mathematica, in its wisdom, considers to be "optimal."
2 Laboratory 2B.nb

Note that (and how) the rubber band has been designed to get thicker as it gets shorter. The right wall was
included as a way of forcing all frames to be drawn to the same scale; otherwise Mathematica would draw each
to its own scale~the scale that Mathematica, in its wisdom, considers to be "optimal."

Watch the movie, then delete the film strip and Save.

In the following exercise we create images of constant figure but changing color:

In[7]:= AnimateB
p 2 p 2
1 + CosA 20 nE 1 + SinA 20 nE
ShowBGraphicsB:RGBColorB , , 0F, Disk@80, 0<, 1D>,
2 2
AspectRatio Ø AutomaticFF, 8n, 0, 40<F

Watch the movie, then delete the film strip and Save.

Any graphic can be animated, whether it be a simple Plot, a ParametricPlot, an ImplicitPlot, a ConÖ
tourPlot…in 2D or 3D. The only constraint is that 3D filmstrips consume a great deal of memory (and can
take a long time to create).

In[8]:= AnimateB

nFF, 8x, 0, 3<, 8y, 0, 3<, Axes Ø NoneF, 8n, 0, 19<F


p
Plot3DBSinBx * y + SinB
10

Save.

Built into Mathematica is a valuable resource which we illustrate as it relates to the following surface:
wave = Plot3D@Sin@x * yD, 8x, 0, 3<, 8y, 0, 3<, Axes Ø NoneD
H*Here we have recreated the first frame in the preceding movie.*L
In[9]:=

H*The AxesØNone is essential to the success of what we are about to do.*L

‡ Exporting Mathematica Graphics to TeX


Click on a cell containing the graphic to Select it: it will acquire a frame with handles. Open File > Save
Selection As… > PDF… . From there it can be imported (by any of a variety of commands) into your TEX
document.
Relatedly…suppose you have done a calculation~for example

In[14]:= ‡ x ArcTan@xD „ x

~and want to insert the result into your TEX document. The command

In[15]:= TeXForm@%D

automatically translates the output into TEX code, which can be pasted directly into your document.
Laboratory 2B.nb 3

automatically translates the output into TEX code, which can be pasted directly into your document.

In[16]:= ? TeXForm

But it is unremarked in the literature that the designers of Mathematica tacitly presume that you be running
LaTEX (or so I judge from the occurance of \frac, which is a LaTEX command, and meaningless in plain
TEX);

Installing Standard Add-on Packages

These, as you have already seen, supply Mathematica with some of its most valuable resources. One should
take steps to become familiar with them.
A safer procedure~which we have many times used already~is to enter a command of the form Needs["DisÖ
creteMath`CombinatorialFunctions`"], which writes into the kernel only when it is proper/appropriate
to do so.
In[17]:= ? Needs

I take advantage of this opportunity to introduce a few packages of miscellaneous interest.

Some Miscellaneous Resources

‡ Physical Constants
In[18]:= Needs@"PhysicalConstants`"D

In[19]:= PlanckConstant

In[20]:= SpeedOfLight

In[21]:= EarthRadius

In[22]:= FineStructureConstant

In[23]:= 1ê%

Use the Browser to discover what physical constants are available. We will return to this topic in Laboratory 5.
4 Laboratory 2B.nb

Use the Browser to discover what physical constants are available. We will return to this topic in Laboratory 5.

‡ Conversion from One System of Units to Another


In[24]:= Needs@"Units`"D

In[25]:= Convert@95 Calorie, ErgD

In[26]:= Convert@16 Mile, MeterD

In[27]:= Convert@1 Year, SecondD

In[28]:= Convert@SolarMass, AtomicMassUnitD

In[29]:= MKS@65 Mile ê HourD

In[30]:= CGS@65 Mile ê HourD

See the Browser for further examples, discussion. We will return also to this topic in Laboratory 5.

‡ Calendar
In[31]:= Needs@"Calendar`"D

Tanja was born on 16 December 1968. From

In[32]:= DayOfWeek@81968, 12, 16<D

I am reminded that she was born on a Monday. From

In[33]:= DaysBetween@81968, 12, 16<, 82000, 6, 8<D

I learn that as of the date of writing she was 11,497 days old, and that

In[34]:= Convert@11 497 Day, SecondD

she is approaching her one billionth birthsecond. That, I find…

In[35]:= Convert@1 000 000 000 Second, DayD

F
312 500 Day
In[36]:= NB
27

In[37]:= DaysPlus@81968, 12, 16<, 11 574D

…will actually occur on the August 24, 2000, when she will be
In[38]:= Convert@1 000 000 000 Second, YearD êê N

old.

‡ Maps
Laboratory 2B.nb 5

Maps
In[39]:= Needs@"WorldPlot`"D

In[40]:= WorldPlot@8World, RandomColors<D;H*Clickêdrag to enlarge*L

In[41]:= World

Maps are susceptible to many optional variations, but the results are in all cases pretty schematic. See the
Browser for details.

Save.

Make sure that sound is on.

‡ Audio
Mathematica ships with a built-in ability to turn waveforms f(t) into sound:

In[42]:= ? Play

In[43]:= Play@Sin@2 p 440 tD, 8t, 0, 3<D

The sonogram is often uninformative, but occasionally it does provide a useful "second handle" on your acous-
tic experience:

Beats

In[44]:= Play@Sin@2 p 440 tD + Sin@2 p 441 tD, 8t, 0, 3<D

Twang

, 8t, 0, 3<F
t
-
In[45]:= PlayBSin@2 p 440 tD ‰ 0.5

Save.

Perfect Chords: Why Do They Sound So Unmusical?

, 8t, 0, 3<F
2 -
t

In[46]:= octave = PlayB Sin@2 p 440 tD + SinB2 p 440 µ tF ‰ 0.5

, 8t, 0, 3<F
3 -
t

In[47]:= perfectfifth = PlayB Sin@2 p 440 tD + SinB2 p 440 µ tF ‰ 0.5


6 Laboratory 2B.nb

, 8t, 0, 3<F
4 -
t

In[48]:= majorthird = PlayB Sin@2 p 440 tD + SinB2 p 440 µ tF ‰ 0.5

, 8t, 0, 3<F
5 t
-
In[49]:= temperedthird = PlayBKSin@2 p 440 tD + SinB2 p 440 2 12 tFO ‰ 0.5

H* Note the occurence of beats in the harmonics *L

Later we will be in position to inquire in quantitative detail into the physical origin of those beats.

An Non-acoustic Application of Audio

Finally we "listen" to the quantum state of a uniformly accelerated particle

In[50]:= Plot@AiryAi@-10 Hx - 1LD, 8x, 0, 5<D

In[51]:= Play@AiryAi@-100 Hx - 1LD, 8x, 0, 5<D

Note that conversion from graphical display to audio display required adjustment of a parameter.

The rising pitch is not entirely obvious to the eye, but quite obvious to the ear: it permits you to "hear the
acceleration," and invites inquiry into the functional form of the Airy function.

Save.

Additional audio resources are made available this way:

In[52]:= Needs@"Audio`"D

In[53]:= ? Waveform

In[54]:= Options@WaveformD

In[55]:= sinusoidA = Waveform@Sinusoid, 440, 1D

In[56]:= Show@%D;

Mathematica requires Show where you might have expected Play (preempted) or Listen. Note, by the way, the speaker icon that
decorates the top of the cell bar when the cell contains audio data.

In[57]:= Waveform@Sawtooth, 440, 1D êê Show

In[58]:= Waveform@Sawtooth, 440, 1, Overtones Ø 4D êê Show

Construction of a Short Tempered Scale

2 12 440 êê N
2

In[59]:=

In[60]:= triangleB = Waveform@Triangle, 493.883, 1D êê Show


Laboratory 2B.nb 7

2 12 440 êê N
4

In[61]:=

In[62]:= squareCsharp = Waveform@Square, 554.365, 1D êê Show

2 12 440 êê N
5

In[63]:=

In[64]:= sawtoothD = Waveform@Sawtooth, 587.33, 1D êê Show

In[65]:= Show@sinusoidA, triangleB, squareCsharp, sawtoothDD

Also available in the Audio package are

In[66]:= ? AmplitudeModulation

In[67]:= ? RingModulation

In[68]:= AmplitudeModulation@200, 500, 1, 2, RingModulation Ø TrueD êê Show

In[69]:= ? FrequencyModulation

In[70]:= FrequencyModulation@660, 87, 70<, 2D êê Show

Save.

If you have special interest in the musical aspects of this topic you might want to experiment with

In[71]:= Needs@"Music`"D

In[72]:= ? Scale

In[73]:= temperedCmajor = Scale@TemperedMajor, 256, 3D êê Show

In[74]:= justCmajor = Scale@JustMajor, 256, 3D êê Show

You can see the difference; could you hear it?

Mathematica provides means to undertake sophisticated analysis of images and signals. There are many
references.
8 Laboratory 2B.nb

Finding Things in Notebooks

We have learned to turn off graphics in order to conserve memory. This, unfortunately, makes it a little diffi-
cult to discover~when you want it again~where in the notebook the in question graphic occurred. Descriptive
text, if inserted on the occasion, helps…but in a long notebook that can take awhile to scan the text. Happily,
there is a better way:
Suppose you have interest in returning to the discussion of quantum oscillators. Open Edit >Find> Find… (or
simply hit Ì-F ), activate the Ignore case and Wrap around buttons, write "quantum" under Search for: and
hit the Find All button, and use Next to advance from occurrence to occurrence until you find the "quantum"
you had in mind.
Or suppose (as happened to me) you use a "GrayScale" option in an effort to make a gray line, and find that it
does not work. But earlier we did have success; how did we do it? A search from "gray" leads immediately to
In[21], where we discover that the correct term is GrayLevel.
The Help menu provides, in fact, many useful resources additional to the one I have described.

Save.
Physicist's Introduction to Mathematica
Physics 200 Physics 50 Lab Revised for V6.0
Fall Semester 2000 Spring Semester 2006 Summer 2007
Nicholas Wheeler John Boccio John Boccio
REED COLLEGE Swarthmore College Swarthmore College
V4.0 Revised for V5.0

Laboratory 3
Part A

Algebra

We look first to the tools in File > Palettes > BasicCalculations > Algebra > Polynomial Manipulation.

Mathematica looks upon Hx + yL7 as a primitive object.


In[2]:= Hx + yL7

But it will expand that binomial if you ask it to:

In[3]:= ? Expand

In[4]:= Options@ExpandD

Here follow some examples:


In[5]:= ExpandAHx + yL7 E

In[6]:= ExpandAI2 + 3 x + 17 x2 M Ix2 - 9M Ix2 + 25ME

In[7]:= ExpandAI2 + 3 x + 17 x2 M Ix2 - 9M Ix2 + 25ME êê TraditionalForm

Standardly the powers xn are in ascending order. The command //TraditionalForm reverses the order and
adjusts the font.
ExpandAH1 + xL3 + H2 + xL3 + H1 + yL2 , 1 + xE
H*Expands only the part containing the stated pattern*L
In[8]:=

Look up Expand in the Browser for finer details and further examples. This "look up" remark pertains to every command we will be
encountering. It is, in fact, a recommended general practice~one I will henceforth assume you have adopted, and do as a matter of
course.

The action of Together is similarly self-explanatory, and opposite to that of Apart:


2 Laboratory 3A.nb

The action of Together is similarly self-explanatory, and opposite to that of Apart:


In[9]:= ? Together

In[10]:= ? Apart

F
a c
In[11]:= TogetherB +
b d

F
bc+ad
In[12]:= ApartB
bd

REMARK: It is often more convenient to use post-commands to achieve the same effect:

êê Together
a c
In[13]:= +
b d

In[14]:= % êê Apart

As a third alternative, one could use the palette buttons Together[‡]and Apart[‡].

The Apart command is used to produce the partial fraction representation of ratios, which is often useful in
pure/applied mathematical work:

F
1
Hx - aL Hx - bL
In[15]:= ApartB

One uses partial fractions to "separate the singularities," as in the following little example:

, 8x, 0, 3<F;
1
Hx - 1L Hx - 2L
In[16]:= PlotB

êê Apart
1
Hx - 1L Hx - 2L
In[17]:=

>, 8x, 0, 3<,


1 1
In[18]:= PlotB: ,-
-2 + x -1 + x
PlotStyle Ø 8RGBColor@1, 0, 0D, RGBColor@0, 0, 1D<F;

Here are some slightly more complicated examples:


Laboratory 3A.nb 3

êê Apart
1
In[19]:=
x2 - a2

êê Apart
1
In[20]:=
x2 + a2

Why did decomposition fail in the latter case? Because we had not informed Mathematica that we are willing to
introduce  factors, which in this instance would be required.
H1 + xL H2 + xL H7 + xL
F
H1 + xL H3 + xL I1 + 2 x + 3 x2 M
In[21]:= ApartB

One should be aware also of the following commands:

In[22]:= ? Cancel

In[23]:= ? ExpandDenominator

In[24]:= ? ExpandNumerator

H1 + xL H2 + xL H7 + xL
F
H1 + xL H3 + xL I1 + 2 x + 3 x2 M
In[25]:= CancelB

H1 + xL H2 + xL H7 + xL
F
H1 + xL H3 + xL I1 + 2 x + 3 x2 M
In[26]:= ExpandDenominatorB

H1 + xL H2 + xL H7 + xL
F
H1 + xL H3 + xL I1 + 2 x + 3 x2 M
In[27]:= ExpandNumeratorB

Note that the latter two commands have some cancellation capability built-in: both automatically got rid of the
(1+x) factors.

One should not confuse the number-theoretic command

In[28]:= ? FactorInteger

(pick an integer and try it) with the algebraic command

In[29]:= ? Factor

In[30]:= Options@FactorD

though both~unlike the algebraic commands considered thus far~display a preoccupation with the integers
(or, by extension, with their complex generalizations, the "Gaussian integers").
In[31]:= FactorA17 x6 + 3 x5 + 274 x4 + 48 x3 - 3793 x2 - 675 x - 450E

The term (25+x2 ) does not factor on the reals, but does if you bring  = -1 into play:

In[32]:= FactorA25 + x2 , GaussianIntegers Ø TrueE

The example
4 Laboratory 3A.nb

The example

In[33]:= FactorAx2 - 9E

In[34]:= % êê Expand

serves to expose the sense in which Factor and Expand are inverse commands (undo each other); enlarging
upon that example, we have
In[35]:= FactorA25 + x2 , GaussianIntegers Ø TrueE

In[36]:= % êê Expand

But factoring 2+3x+17x2 leads away from the (Gaussian) integers~amounts to looking for roots of the polynomial:

Save.

‡ Finding the Roots of a Polynomial


The celebrated Fundamental Theorem of Algebra (Gauss) asserts that every polynomial of degree n
(coefficients real or complex) possesses n roots (real or complex). Those can be discovered by means of the
following commands:
In[37]:= ? Solve

In[38]:= ? NSolve

In[39]:= SolveA2 + 3 x + 17 x2 ã 0, xE

In[40]:= NSolveA2 + 3 x + 17 x2 ã 0, xE

The quadratic formula has been known for since antiquity


In[41]:= SolveAa x2 + b x + c ã 0, xE

One can without loss of generality arrange to have the the coefficient of xn be unity, and the coefficient of xn-1
be zero. Assume those adjustments to have been made. In the 16th Century Jerome Cardan, Niccolo Tartaglia
and Ludovico Ferrari carried the problem of solving the cubic and quartic as far as one could without knowl-
edge of complex numbers (the invention of which was stimulated by their success):
In[42]:= SolveA x3 + b x + c ã 0, xE

In[43]:= SolveA x4 + a x2 + b x + c ã 0, xE

All efforts to solve the quintic (which everyone expected to be difficult) failed…for what Galois and Abel
showed (early 19th Century) to be this very good reason: solution (in the sense of the preceding formulae) is
impossible, except in special cases. Mathematica has this to say in the general case:
In[44]:= SolveA x5 + w x3 + a x2 + b x + c ã 0, xE

But (approximate) numerical solution is possible in all cases:


Laboratory 3A.nb 5

But (approximate) numerical solution is possible in all cases:

In[45]:= SolveAx5 + x3 + 2 x2 + 3 x + 4 ã 0, xE

In[46]:= NSolveAx5 + x3 + 2 x2 + 3 x + 4 ã 0, xE êê TableForm

Here is a more acccurate version of the same statement:

In[47]:= NSolveAx5 + x3 + 2 x2 + 3 x + 4 ã 0, x, 20E êê TableForm

Now for a couple of useful definitions. The first permits one to plot lists of complex numbers

In[48]:= ComplexListPlot@points_, options__D :=

options, AxesLabel Ø 8"Re", "Im"<D


ListPlot@Map@8Re@Ò1D, Im@Ò1D< &, pointsD,

and works like this:


In[49]:= ComplexListPlot@8-1 + Â, 2 + Â, 1 - 2 Â<, PlotStyle Ø PointSize@0.03DD;

We now use that tool to plot the complex numbers that arise as roots of a polynomial:
RootPlot@expr_, x_D :=
ComplexListPlot@x ê. N@Solve@expr ã 0, xDD,
In[50]:=

AspectRatio Ø Automatic, PlotStyle Ø PointSize@0.03DD

We use this command to plot the roots of the quintic used in our recent numerical example:

In[51]:= RootPlotAx5 + x3 + 2 x2 + 3 x + 4, xE;H*Note that ã0 is not called for*L

Another example:

In[52]:= RootPlotAx6 - 2 x2 + 4 x + 4, xE;

Save.

When we plot the polynomial we see the real roots as axis-crossings, but only an obscure hint of the complex
roots:
In[53]:= PlotAx6 - 2 x2 + 4 x + 4, 8x, -1.5, 1.5<E;

In[54]:= RootPlotAx17 - 1, xE;

In[55]:= RootPlotA
1 + x + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + x12 + x13 + x14 + x15 + x16 , xE;

The figures are so similar because

NOTE: The following line is grayed to emphasize that, though presented in Input style, it is not to be entered as input. Enter
only commands that wear In[ ] labels. I will adhere to this convention.

1 + x + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + x12 + x13 + x14 + x15 + x16

and
6 Laboratory 3A.nb

and
x17 - 1

are very closely related:

, 8x, 0, 17<F
x17 - 1
In[56]:= SeriesB
x-1

Removal of the (x - 1) factor has erased one of the dots (roots). The roots in question are, of course, 17th roots of unity:

In[57]:= SolveAx17 - 1 ã 0, xE êê TableForm

The Little Example Upon Which I Hang a Digression

The roots of
15
x4 - x2 + 1 ã 0
9

are all complex

x2 + 1 ã 0, xFF êê TableForm
15
In[58]:= NBSolveBx4 -
9

15
In[59]:= RootPlotBx4 - x2 + 1, xF;
9

and don't show up in graphs of the form

x2 + 1, 8x, -2, 2<, PlotRange Ø 80, 4.0<F;


15
In[60]:= PlotBx4 -
9

That observation motivates the following…

Solving Systems of Simultaneous Equations

Generic Pair of Coupled Linear Equations

In[73]:= Solve@8a x + b y ã p, c x + d y ã q<, 8x, y<D

In[74]:= Solve@8a x + b y ã 0, c x + d y ã 0<, 8x, y<D êê TableForm


Laboratory 3A.nb 7

Solution of an Inhomogeneous Linear Triple

In[75]:= Solve@81 x + 2 y + 3 z ã p, 4 x + 5 y + 6 z ã q, 7 x + 8 y + 9 z ã r<, 8x, y, r<D êê


TableForm

Nonlinear Pair

In[76]:= SolveA9x2 + y2 ã 2, x + y ã 1=, 8x, y<E êê TableForm

In[77]:= NSolveA9x2 + y2 ã 2, x + y ã 1=, 8x, y<E êê TableForm

In[78]:= NSolveA9x2 + y2 ã 2, x + y ã 1=, 8x, y<, 20E êê TableForm

Here is a graphic respresentation of what Mathematica has just accomplished:


ContourPlotA9x2 + y2 ã 2, x + y ã 1=, 8x, -2, 2<, 8y, -2, 2<,
ContourStyle Ø 8RGBColor@1, 0, 0D, RGBColor@0, 0, 1D<E
In[80]:=

In[81]:= SolveA9x2 ã 1, x2 ã 2=, xEH*Obviously there is NO


solution. See how Mathematica conveys that information.*L

And here it does the job, but publishes a disclaimer:

In[82]:= NSolveA2n ã 10 000, nE

Trigonometry

Commands like Expand[‡], Factor[‡] and Simplify[‡] are of a type known as formula manipulation
commands. We experiment now with some "trigonometrically informed" relatives of those. The simple com-
mands in question are
In[93]:= ? TrigExpand

In[94]:= ? TrigFactor

In[95]:= ? TrigReduce

In[96]:= ? TrigToExp

In[97]:= ? ExpToTrig

A few examples will make clear what they do:

In[98]:= TrigExpand@Cos@a + bDD


8 Laboratory 3A.nb

In[99]:= TrigExpand@Cos@a + b + gDD

In[100]:= TrigFactor@Cos@aD + Cos@bDD

In[101]:= TrigExpand@%D

In[102]:= Simplify@%D

In[103]:= TrigReduceACos@aD3 E

In[104]:= TrigReduce@Cos@aD Sin@bDD

In[105]:= TrigFactor@%D

In[106]:= TrigToExpASin@aD3 E

In[107]:= ExpToTrigA‰Â q E

In[108]:= SimplifyASin@aD2 + Cos@aD2 E

With the aid of the preceding commands one can~with experience~reconstruct and enlarge upon the standard
lists of trigonometric identities. Experience is required because any given trigonometric expression can be
written in a zillion ways, and one must learn how to tell Mathematica the goal one has in mind.
And in the latter regard one must be braced for some surprises. For example: suppose~with

In[109]:= TrigExpandAHSin@aD + Sin@bDL2 E

in mind~we ask for

In[110]:= TrigExpandAHSin@10 tD + Sin@11 tDL2 E

This is an unanticipated result. What's going on? Mathematica interprets Sin[10 t] to mean
Sin[t+t+t+t+t+t+t+t+t+t]because 10 is an integer. To get the result we anticipated we must ask Mathe-
matica to think of 10 as just a real number:

In[111]:= TrigExpandAHSin@10.0 tD + Sin@11.0 tDL2 E

Save

Some Elementary Physical Applications

Superimposed harmonic signals of the unequal amplitude but nearly the same frequency yield a signal of the
form:
1
In[112]:= compositesignal@t_D := Sin@100 tD + Sin@102 tD
2

and when fed into an oscilloscope yield an image like this:

In[113]:= Plot@compositesignal@tD, 8t, 0, 5<D

of which this provides (at augmented frequency) an audio representation:


Laboratory 3A.nb 9

of which this provides (at augmented frequency) an audio representation:

In[114]:= Needs@"Audio`"D

Sin@102 µ 2 p tD, 8t, 0, 3<F


1
In[115]:= PlayBSin@100 µ 2 p tD +
2

But if the signal is fed into an intensity detector we see/hear something quite different:
2
1
In[116]:= intensity@t_D := Sin@100 tD + Sin@102 tD
2

In[117]:= Plot@intensity@tD, 8t, 0, 5<D;

, 8t, 0, 3<F
2
1
In[118]:= PlayB Sin@100 µ 2 p tD + Sin@102 µ 2 p tD
2
From

F
2
1
In[119]:= TrigReduceB Sin@100.0 tD + Sin@102.0 tD
2

we see that the output of the intensity detector contains a DC component, and two frequencies not present in the
original signal: those are sum and difference frequencies~in a word: sidebands. Here is an illustration of the
more general situation:

In[120]:= TrigReduceAHSin@w1 tD + Sin@w2 tD + Sin@w3 tDL2 E

Save

Matrix Algebra

To create a matrix it is simplest to proceed this way: openInsert > Table/Matrix>New…,select the desired
number of rows/columns, and hit the OK button. You will create something like this:
Ñ Ñ Ñ Ñ
Ñ Ñ Ñ Ñ
Ñ Ñ Ñ Ñ
Ñ Ñ Ñ Ñ

Note also the presence of the "Fill with" and "Fill diagonal" buttons, which permit you to create things like
10 Laboratory 3A.nb

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

and
0 Ñ Ñ Ñ
Ñ 0 Ñ Ñ
Ñ Ñ 0 Ñ
Ñ Ñ Ñ 0

with a single keystroke. Often useful also is the command

In[121]:= IdentityMatrix@4D êê MatrixForm

Other techniques for creating matrices do exist. Open File > Palettes > BasicCalculations > Lists and Matrices and read Creating
Lists and Matrices.

Proceeding thus~and making heavy use of Copy/Paste as we Í from · to ·~we create the following:

In[122]:= rowvector = H a1 a2 a3 L
b1
columnvector = b2
b3
m11 m12 m13
matrix = m21 m22 m23
m31 m32 m33

Mathematica reveals here its instinct to display matrices as lists of lists…which is, however, easily overridden:
rowvector êê MatrixForm H*Compare that with the following:*L
rowvector êê TraditionalForm
In[125]:=

In[127]:= columnvector êê MatrixForm

In[128]:= matrix êê MatrixForm

CAUTION: Do not use //MatrixForm when first defining a matrix, or commands active upon the matrix (see below) will not work
properly.

To discover your basic resources for manipulating matrices, open File > BasicCalculations > Lists and Matri-
ces > Matrix Operations, where you will find buttons associated with each such resource. Thus

M=K O
a b
In[129]:=
c d

In[130]:= Tr@MD

In[131]:= Det@MD

In[132]:= HÑ Ñ ÑL
Laboratory 3A.nb 11

In[133]:= Inverse@MD êê MatrixForm

Less useful (because responsive to a question the answer to which is seldom in doubt) is the command

In[134]:= Dimensions@rowvectorD
Dimensions@columnvectorD
Dimensions@matrixD

Matrix multiplication is accomplished not with a * but with a . as illustrated below:

A=K O
a11 a12
In[137]:=
a21 a22

B=K O
b11 b12
b21 b22

In[139]:= A.B êê MatrixForm

H*Gives row vector dotted into column vector: the familiar "\!\H\*
In[140]:= rowvector.columnvector

StyleBox@\"dot\",\nFontColor->RGBColor@1, 0, 0DD\L\!\H\*
StyleBox@\" \",\nFontColor->RGBColor@1, 0, 0DD\L\!\H\*
StyleBox@\"product\",\nFontColor->RGBColor@1, 0, 0DD\L."*L

In[141]:= % êê MatrixForm

In[142]:= columnvector.rowvector êê MatrixForm

The commands rowvector.rowvector and columnvector.columnvector are meaningless (except in


the one-dimensional case), as Mathematica is quick to remind you:
In[143]:= rowvector.rowvector

In[144]:= columnvector.columnvector

But the object (actually a simple list)

In[145]:= eithervector = 8c1 , c2 , c3 <

can in some contexts be used as if it were "simultaneously row/column:"

In[146]:= eithervector.eithervector

In[147]:= matrix.eithervector

In[148]:= eithervector.matrix

Because matrix multiplication is a bit quirky, one must take special steps to raise a square matrix to a power;
this is accomplished with the assistance of
In[149]:= ? MatrixPower

S=K O
0 -1
In[150]:=
1 0
12 Laboratory 3A.nb

In[151]:= MatrixPower@S, 2D êê MatrixForm

R=‚ qn MatrixPower@S, nD êê MatrixFormH*Mathematica


6
1
In[152]:=
n=0
n!

returns nothing useful if we set the upper limit to infinity.*L

Pretty clearly

R=K O
Cos@qD -Sin@qD
In[153]:=
Sin@qD Cos@qD

which we recognize to be a rotation matrix:

In[154]:= Simplify@Transpose@RD == Inverse@RDD

Actually, Mathematica provides a command which eliminates the guess work, and is very useful in a great
variety of pure/applied contexts:
In[155]:= ? MatrixExp

In[156]:= MatrixExp@q SD êê MatrixForm

There exists a second kind of matrix multiplication which is indispensible in some group-theoretic and quantum
mechanical contexts: I refer to the Kronecker (or "outer") product, which yields a matrix with matrix-valued
elements. The following description
In[157]:= ? Outer

is opaque because "outer multiplication" is such a general notion. As physicists we have common need only of
the simplest instances of outer multiplication. Recalling that by prior definition
A êê MatrixForm
B êê MatrixForm
In[158]:=

K O
Out[158]//MatrixForm=
a11 a12
a21 a22

K O
Out[159]//MatrixForm=
b11 b12
b21 b22

we construct

In[160]:= Outer@Times, A, BD êê MatrixForm

K O K 12 O
Out[160]//MatrixForm=
a11 b11 a11 b12 a b11 a12 b12
a11 b21 a11 b22 a12 b21 a12 b22
K 21 O K 22 O
a b11 a21 b12 a b11 a22 b12
a21 b21 a21 b22 a22 b21 a22 b22

which has the design

K O
a11 B a12 B
a21 B a22 B

Matrices are lists (of lists), so any command with the attribute "listable" will accept a matrix as its argument:
thus
Laboratory 3A.nb 13

Matrices are lists (of lists), so any command with the attribute "listable" will accept a matrix as its argument:
thus

+ a êê MatrixForm
1 x
In[161]:=
x2 x3

‡ „ x êê MatrixForm
1 x
In[162]:=
x2 x3

In the 2-dimensional case to which I confine these illustrative remarks, the characteristic polynomial of a matrix

In[163]:= M êê MatrixForm

is defined

OF
a-x b
In[164]:= DetBK
c d-x

In Mathematica it results from the command

In[165]:= CharacteristicPolynomial@M, xD

The celebrated (and very often valuable) Cayley-Hamilton Theorem asserts~remarkably~that "every matrix
satisfies its own characteristic equation" and in the present instance we do indeed have
In[166]:= identity = IdentityMatrix@2D
nullmatrix = K O
0 0
0 0

In[168]:= H-b c + a dL identity - a M - d M + M.M ã nullmatrix

The "eigenvalues" of a matrix are the roots of its characteristic polynomial. To discover those we might proceed

In[169]:= Solve@CharacteristicPolynomial@M, xD ã 0, xD êê TableForm

but Mathematica provides a better way:

In[170]:= ? Eigenvalues

In[171]:= Eigenvalues@MD êê TableForm

Thus far we have asked Mathematica to do matrix-theoretic things we could as easily have done by hand. The
power of Mathematica is more clearly evident in higher-dimensional situations. To have some representative
material to work with, we construct a 5 by 5 matrix with random real-valued elements:
In[172]:= randomrealmatrix = 8RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D,
RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D,
RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D,
RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D,
RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D<

In[173]:= % êê MatrixForm

Hrandomrealmatrix + Transpose@randomrealmatrixDL
1
In[174]:= symmetricpart =
2
14 Laboratory 3A.nb

In[175]:= % êê MatrixForm

To construct the determinant of such a matrix you would have to multiply 5 numbers in 5! combinations and
add the (appropriately signed) results; observe how quickly Mathematica does the job:
In[176]:= Det@randomrealmatrixD

We find that the eigenvalues are typically complex, but occur in conjugate pairs, and that in odd-dimensional
cases at least one is necessarily real:
In[177]:= Eigenvalues@randomrealmatrixD êê TableForm

We plot the distribution of those complex eigenvalues:

In[178]:= CharacteristicPolynomial@randomrealmatrix, xD

Look similary to the real symmetric part of the preceding matrix; we find that all the eigenvalues are real:
In[180]:= Eigenvalues@symmetricpartD êê TableForm

In[181]:= CharacteristicPolynomial@symmetricpart, xD

Save

Now construct a 5 by 5 matrix with random complex-valued elements


randomcomplexmatrix =
8RandomComplex@8-2 - 2 Â,
In[183]:=
2 + 2 Â<, 5, WorkingPrecision Ø 6D,
RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D,
RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D,
RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D,
RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D<

Here and below I have used ; to surpress the screen-filling but not-very-informative output.

Construct also the hermitian part of that matrix:

In[184]:= hermitian =

Hrandomcomplexmatrix + Transpose@Conjugate@randomcomplexmatrixDDL
1
2

In[185]:= Eigenvalues@hermitianD êê TableForm

The imaginary parts are pretty clearly computational artifacts, and are easily chopped off:

In[186]:= spectrum = Chop@%D

In[187]:= ? Chop

The eigenvectors of a matrix arise by solution of an equation of the form


Laboratory 3A.nb 15

In[191]:= matrix.eigenvector ã number * eigenvector

which is possible iff "number" is in fact one or another of the eigenvalues of the matrix. This can be accom-
plished by the command
In[192]:= ? Eigenvectors

(which is available as a button on the Matrix Operations palette) but it is usually more informative/efficient to
use
In[193]:= ? Eigensystem

The following simple example is designed to show how this works:

tracelesssymmetric = K O;
1 2
In[194]:=
2 -1

In[195]:= Eigensystem@tracelesssymmetricD êê TableForm

We use that information to define

In[196]:= eigenvalue1 = - 5
1- 5
eigenvector1 = 2
1
eigenvalue2 = 5
1+ 5
eigenvector2 = 2
1

and find that indeed

In[200]:= tracelesssymmetric.eigenvector1 ã eigenvalue1 * eigenvector1

Ignore the cautionary quibble and proceed:

In[201]:= Simplify@%D

In[202]:= tracelesssymmetric.eigenvector2 ã eigenvalue2 * eigenvector2 êê Simplify

The eigenvectors are, as presented, not normalized

In[203]:= squaredlength1 = Transpose@eigenvector1D.eigenvector1 êê N

In[204]:= squaredlength2 = Transpose@eigenvector2D.eigenvector2 êê N

a1 = GraphicsB:ArrowB:80, 0<, : J1 + 5 N, 1>>F>F;


1
In[77]:=
2

a2 = GraphicsB:ArrowB:80, 0<, : J1 + 5 N, 1>>F>F;


1
In[78]:=
2

In[79]:= Show@a1, a2D

We see the eigenvectors to be orthogonal, which is confirmed by the observation that


16 Laboratory 3A.nb

In[207]:= dotproduct = Transpose@eigenvector1D.eigenvector2 êê Simplify

A classic argument shows orthogonality to be, in fact, an automatic consequence of the assumed symmetry of
our real square matrix; this fact has many physical implications, and is the ultimate source of the "normal
mode" terminology encountered in the theory of coupled oscillators.

Save, then continue to Part B


Physicist's Introduction to Mathematica
Laboratory 3
Part B

Calculus

For indication of your most basic resources, see the Calculus or BasicInput palettes. They work just as you
would expect them to. We look first to

‡ Simple definite/indefinite integrals


In[2]:= ? Integrate

‡ Sech@xD „ x H*A typical indefinite integral*L


2
In[3]:=

In[5]:= PlotASech@xD2 , 8x, -3, 3<, Filling Ø AxisE;

‡ Sech@xD „ x H*A typical definite integral*L


3
2
In[6]:=
-3

In[7]:= N@%, 25D

Mathematica can often manage singular integrands without difificulty:


3 1
In[8]:= „x
-3 x2

, 8x, -3, 3<, PlotRange Ø 80, 50<, Filling Ø AxisF


1
In[9]:= PlotB
x2

‡ DiracDelta@y - 1D „ y
x
In[10]:=

In[11]:= Plot@UnitStep@-1 + xD, 8x, -3, 3<D

and is even capable of some "singular differentiation":


In[12]:= ∂x UnitStep@-1 + xD

Built into Mathematica is a vast integral table, and a powerful integration capability. Yet the integrals of many
functions~even quite simple functions~cannot be expressed in terms of named functions. Here is how Mathe-
matica responds in such a case:
2 Laboratory 3B.nb

Built into Mathematica is a vast integral table, and a powerful integration capability. Yet the integrals of many
functions~even quite simple functions~cannot be expressed in terms of named functions. Here is how Mathe-
matica responds in such a case:


1
In[13]:= ArcTan@xD „ x
0

‡ Numerical integration
But from

In[14]:= FilledPlotB ArcTan@xD , 8x, 0, 1<F

we see that the definite integral in question is a perfectly reasonable thing to ask for~a certain number. It can
be got this way:
In[15]:= ? NIntegrate

In[16]:= NIntegrateB ArcTan@xD , 8x, 0, 1<F

‡ Functions defined by integrals


Often Mathematica responds in ways you might not think are immediately informative:

‡ CosAx E „ x
2
In[17]:=

Mathematica is telling you that your obligation at this point is to learn some mathematics! Specifically, to learn
about Fresnel functions. As first steps toward that objective you might proceed
In[18]:= ? FresnelC

In[19]:= Plot@FresnelC@xD, 8x, 0, 6<, PlotRange Ø AllD

Finally, you should look up "Fresnel" in Help > Find Selected Functions…
Historically, many functions are defined by integrals, and you can do the same. In a simple instance you might
proceed
In[20]:= g@t_D := -g

v@t_D := ‡ g@uD „ u + v0
t

y@t_D := ‡ v@wD „ w + y0
t

In[23]:= g@tD
v@tD
y@tD

Less trivially: the function defined as follows

q@xD := ‡
x 1
In[26]:= „x
0
1- x2

is really just the already-named function arcsine(x), as can be demonstrated this way:
Laboratory 3B.nb 3

is really just the already-named function arcsine(x), as can be demonstrated this way:
In[27]:= Sin@q@xDD

In[28]:= Plot@Evaluate@q@xD, 8x, 0, 1<DD;

‡ Multiple integrals
The idea just presented assumes particular importance when one looks to multiple integrals. Suppose, for
instance, you had interest in integrating sin(xy) over the triangular region 0 < x < y < 1. You might begin with the
command

‡ ‡ Sin@x yD „ y „ x
1 x
In[29]:=
0 0

Mathematica appears to be telling us that it does not know how to do the second integral in closed form; we
check to see if that is so:

‡ Sin@x yD „ y
x
In[30]:=
0

The integrand thus produced leads, however, to a perfectly good integral (the integrand is never infinite, or
otherwise undefined); this we conclude from the following figure:
CosAx2 E
, 8x, 0, 1<F, PlotRange Ø AllF
1
In[31]:= PlotBEvaluateB -
x x

So we proceed numerically:
CosAx2 E
, 8x, 0, 1<F
1
In[32]:= NIntegrateB -
x x

Save.

‡ Ordinary & partial differentiation


The Basic Input palette provides ∂„ ‡ and ∂„ ,„ ‡ buttons that work this way:

SinAx2 E + CosAy2 E
In[33]:= ∂x
1 - x2 - y2

SinAx2 E + CosAy2 E
In[34]:= ∂y
1 - x2 - y2

We compute "cross derivatives" and~as expected~discover them to be equal:


4 Laboratory 3B.nb

SinAx2 E + CosAy2 E
In[35]:= ∂x,y
1 - x2 - y2

SinAx2 E + CosAy2 E
In[36]:= ∂y,x
1 - x2 - y2

If you use the ∂Ñ É button to create

In[37]:= ∂8x,5< x10 H*you get the 5th derivative:*L

The effect of the buttons employed above can be achieved directly from the keyboard: write Âpd to create ∂
, then type ‚- (control-dash) to creat the subscript box; type the subscript, to create something like ∂x . Then
hit ‚¯ to move the cursor back to the main line, where you type the function to be differentiated.
But often it is quicker/easier to use the following simple command:

In[38]:= ?D

Thus
SinAx2 E + CosAy2 E
In[39]:= DB , xF
1- x2 - y2

SinAx2 E + CosAy2 E
In[40]:= DB , x, yF
1- x2 - y2

In handwritten work we often employ prime ' to denote differentiation when we are concerned with functions
of a single variable. Mathematica recognizes~and itself sometimes employs~that notation, but only when the
object being differentiation is a function, not an expression:
In[41]:= Clear@f, gD

SinAx2 E
In[42]:= f@x_D :=
1 - x2

In[43]:= f '@xD H*A prime differentiates the function...*L

SinAx2 E
In[44]:= ' H*...but not the bare expression:*L
1- x2

It is easy to ask for the value assumed by f'[x] when x is assigned a particular value
In[45]:= f '@.5D

and we can use multiple primes to multiply differentiate:

In[46]:= g@x_D := x10


Laboratory 3B.nb 5

In[47]:= g '@xD
g ''@xD
g '''@xD

Alternatively we might have commanded

D@g@xD, 8x, 2<D


In[50]:= D@g@xD, xD

D@g@xD, 8x, 3<D

Dummy Functions

Suppose we write f[x] and g[x] to indicate that we are thinking about a couple of generic (or "dummy")
functions~functions to which we have assigned no specific meaning. Mathematica is content to work at such a
level of abstraction, and is easily able to return all the standard relationships (in, if you request, generalized
form):
In[53]:= Clear@f, gD

In[54]:= ∂x Hf@xD g@xDL H*Product Rule*L

NOTE that Mathematica itself has here elected to use prime notation.

H*Quotient Rule*L
f@xD
In[55]:= ∂x
g@xD

In[56]:= Together@%D

In[57]:= ∂x Log@f@xD g@xDD

In[58]:= Simplify@%D

In[59]:= ∂x f@g@xDD H*Chain Rule*L

D@f@g@xDD, 8x, 2<D


H*Higher-order differentiation of a composite function:*L
In[60]:=

In[61]:= D@f@g@xDD, 8x, 3<D

Notice the notation that Mathematica has here adopted to represent derivatives of order greater than 2.

In[62]:= D@f@g@xDD, 8x, 4<D

In[63]:= D@f@xD g@xD, 8x, 2<D H*Leibniz' Rule*L

In[64]:= D@f@xD g@xD, 8x, 3<D

In[65]:= D@f@xD g@xD, 8x, 4<D


6 Laboratory 3B.nb

DB‡ f@uD „ u, xF H*Fundamental Theorem of Calculus*L


x
In[66]:=
0

‡ D@f@uD, uD „ u
x
In[67]:=
0

Mathematica is comfortable also with dummy functions of several variables. For example, we have

In[68]:= D@f@x, yD g@x, yD, x, yD

In[69]:= D@f@x, g@x, yDD, x, yD

etc. Note the notational device used by Mathematica to tell us what has been partially differentiated with
respect to what.

Save.

Implicit Differentiation

This technique is often quite useful, though it is my impression that it is no longer taught in introductory calcu-
lus courses.
Suppose we know of y[x] only that
In[70]:= Clear@x, y, aD

In[71]:= x2 + y2 ã 10 x y + a2

Then

In[72]:= DAx2 + y@xD2 - 10 x y@xD - a2 , xE

surely vanishes; we use this information to obtain a description of y'[x]:


In[73]:= Solve@2 x - 10 y@xD - 10 x y£ @xD + 2 y@xD y£ @xD ã 0, y£ @xDD

To find the 2nd derivative y''[x] we would proceed


-x + 5 y@xD
In[74]:= firstderivative@x_D := -
5 x - y@xD

In[75]:= D@firstderivative@xD, xD

H-x + 5 y@xDL H5 - pL -1 + 5 p
H5 x - y@xDL2
In[76]:= secondderivative@x_, p_D := -
5 x - y@xD

In[77]:= secondderivative@x, firstderivative@xDD

In[78]:= Simplify@%D

But it was announced at the outset that


Laboratory 3B.nb 7

In[79]:= x2 + y2 - 10 x y == a2

so we have finally
24 a2
Hy - 5 xL3
In[80]:= y ''@xD ==

Maxima & Minima

The following commands serve to define a simple function and to locate its extrema:

In[81]:= Clear@fD

In[82]:= f@x_D := x3 - 9 x + 5

In[83]:= Plot@f@xD, 8x, -4, 4<D

In[84]:= Solve@f '@xD ã 0, xD

In[85]:= N@%D

Those results agree with the impression conveyed by the figure. We will decorate the figure to make the point
more vivid:
In[86]:= extrema = 8x, f@xD< ê. %

/. is the ReplaceAll command. Look it up in the Master Index, which provides a good discussion. Here we use it to replace each of
the entries in the preceding list with a pair of numbers deduced from those entries.

Plot@f@xD, 8x, -4, 4<,


Epilog Ø 8PointSize@0.03D, Hue@1D, Map@Point, extremaD<D
In[87]:=

The Epilog command can be used with any command that produces graphics…It allows you to overlay
"graphics primitives" (such as points) on the graphic after it has been rendered. [We adjusted the pointsize and
color to make them more visible.] The Map[Point, extrema] produces a list of primitive point objects, one
for each point in the list we named extrema.

‡ Limits & Series


These, of course, are distinct but closely interrelated topics; I lump them together partly for that reason, and
partly because the Calculus palette juxtaposes the buttons that produce
Limit@‡, Ñ Ø ÑD

Series@‡, 8Ñ, Ñ, Ñ<D

In[88]:= ? Limit

In[89]:= ? Series

First Example
8 Laboratory 3B.nb

First Example

In[90]:= Clear@fD

Sin@xD
In[91]:= f@x_D :=
x

At x = 0 we get the improper construction 0/0, yet from the figure

In[92]:= Plot@f@xD, 8x, -6 p, 6 p<, PlotRange Ø AllD

we see that the function is perfectly well-behaved there, and are not surprised to obtain

In[93]:= Limit@f@xD, x Ø 0D

Expansion about the origin shows how this result is achieved:


In[94]:= Series@f@xD, 8x, 0, 4<D

Also of interest is the statement

In[95]:= Limit@f@xD, x Ø ¶D

Second Example

Look now to the function

In[96]:= Clear@gD

1
In[97]:= g@x_D :=
x

In[98]:= Plot@g@xD, 8x, -1, 1<D

In[99]:= Limit@g@xD, x Ø 0D

Evidently Mathematica has, by default, elected to approach the origin from the right. One can reverse the
direction of approach by modifying the command:
In[100]:= Limit@g@xD, x Ø 0, Direction Ø 1D

Third Example

While the function


‰-x

has well-defined limits


In[101]:= LimitA‰-x , x Ø ¶E
LimitA‰-x , x Ø -¶E

the function
Laboratory 3B.nb 9

Sin@xD

approaches no limit, but forever buzzes within a well-defined interval; Mathematica tells you so:

In[103]:= Limit@Sin@xD, x Ø ¶D
Limit@Sin@xD, x Ø -¶D

Some Series~Familiar & Less Familiar

In[105]:= Series@Log@1 + xD, 8x, 0, 10<D

In[106]:= Series@ArcTan@xD, 8x, 0, 10<D

, 8x, 0, 10<F
1
In[107]:= SeriesB
1-x

F, 8x, 0, 10<F
1 1
In[108]:= SeriesB LogB
1-x 1-x

In the latter connection we note that

, 8n, 1, 10<F
n
1
In[109]:= TableB‚
k=1
k

Finally I reproduce a much more ambitious result, taken from p. 39 of Gradshteyn & Ryzhik's Table of Inte-
grals, Series & Products (1965):

, 8x, 0, 4<F

Cos@k xD
In[110]:= SeriesB‚
k=1 k2

In[111]:= Simplify@%D

Just as interesting integrals are sometimes taken to define numbers/functions, so are interesting series. The
following series serves to define the Bernoulli numbers

, 8t, 0, 10<F
t
In[119]:= SeriesB
‰t - 1

, 8n, 0, 10<F
BernoulliB@nD
In[120]:= TableB
n!

while this celebrated series

‚ n-z

In[121]:=
n=1

serves to define the Riemann zeta function:


In[122]:= ? Zeta

Save.
Physicist's Introduction to Mathematica
Physics 200 Physics 50 Lab Revised for V6.0
Fall Semester 2000 Spring Semester 2006 Summer 2007
Nicholas Wheeler John Boccio John Boccio
REED COLLEGE Swarthmore College Swarthmore College
V4.0 Revised for V5.0

Laboratory 4

Solving Ordinary Differential Equations

Many problems in physics~as also elsewhere in the pure/applied mathematics of the last three centuries~
assume this form: Find the x(t) which, in collaboration with its derivatives, satisfies an equation of the form
F@x@tD, x '@tD, x ''@tD, ...D ã 0

together with prescribed initial/boundary conditions. Newton's 2nd Law provides the classic case in point: it
presents the problem of dynamical motion as the problem of solving
m x ''@tD ã F@x@tDD
Initial conditions : x@t0 D ã x0 and x '@t0 D ã v0

or, more generally, of solving


m x ''@tD ã Fx @x@tD, y@tD, z@tDD
m y ''@tD ã Fy @x@tD, y@tD, z@tDD
m z ''@tD ã Fz @x@tD, y@tD, z@tDD
Six initial conditions required

which comprise a coupled system of 2nd order ODEs.

REMARK: Such equations are called ordinary differential equations because the unknown functions are functions of a single indepen-
dent variable, so only ordinary derivatives are encountered. "Fields" are functions of several independent variables; one therefore
encounters partial derivatives, and is led to the theory of partial differential equations (PDEs)…which traditionally has been thought of
as a different subject altogether, but which Mathematica equips one to approach with equal ease.

The ODE literature presents a bewildering collection of tricks devised by generations of mathematicians to
solve ODEs of this or that specialized type. Most of those tricks pertain exclusively to ODEs that can be solved
in terms of named functions (many "named functions" arose from the theory of ODEs). But many/most of the
ODEs encountered in realistic physical situations elude the network of known tricks: such equations must be
solved numerically. The situation is further complicated by the circumstance that it is difficult, even with a
virtuoso command of the tricks, to know in advance whether or not the particular ODE in hand can be brought
to such a form that it yields to some trick. Today all is changed, simplified, because…
The ODE literature presents a bewildering collection of tricks devised by generations of mathematicians to
solve ODEs of this or that specialized type. Most of those tricks pertain exclusively to ODEs that can be solved
2 in terms of named functions (many "named functions" arose from the theory of ODEs). But many/most Laboratory
of the4A.nb
ODEs encountered in realistic physical situations elude the network of known tricks: such equations must be
solved numerically. The situation is further complicated by the circumstance that it is difficult, even with a
virtuoso command of the tricks, to know in advance whether or not the particular ODE in hand can be brought
to such a form that it yields to some trick. Today all is changed, simplified, because…
• Mathematica knows all the tricks.
• Mathematica permits a simple, unified approach to the solution of ODEs.

In[2]:= ? DSolve

In[3]:= ? NDSolve

Whole books have been written about this subject. Here I must be content to treat only the bare bones of a vast
subject. I will let physical problems provide my motivation.

‡ Exponential Population Growth


Let P[t] describe the size of a population at time t . Population growth can, in the simplest model, be
described
P '@tD ã a P@tD

The general solution is obvious, but let us ask Mathematica to do the work:

In[4]:= DSolve@P '@tD ã a P@tD, P@tD, tD

The output is a replacement list (in this case, a one-element list). C[1] is the name Mathematica gives to the
arbitrary constant of integration.

NOTE: The general solution of an ODE (or system of ODEs) is expected to contain constants of integration equal in number to the
order of the ODE (or system); the present system is of first order, so we encounter only a solitary constant.

A Short Digression~Removing the Braces

The outer { }'s sometimes gets in the way (as we will soon enough see); to strip it away we might command
In[5]:= DSolve@P '@tD ã a P@tD, P@tD, tD êê TableForm

but in more complicated situations that proves not to be such a good idea; if tried in connection with the follow-
ing coupled pair of first-order ODEs (system of second order: note the appearance of both C[1] and C[2] in
the output)
In[6]:= DSolve@8p '@tD ã a q@tD, q '@tD ã b p@tD<, 8p@tD, q@tD<, tD êê TableForm

we find that the output overextends the right side of the page. A better procedure, makes use of these two
commands:
In[7]:= ? First

In[8]:= ? ReplaceAll

First is equivalent to the post-command P1T; both act to pluck the first element from a list:

In[9]:= First@8tom, sally, harry<D

In[10]:= 8tom, sally, harry<P1T


Laboratory 4A.nb 3

In[11]:= 8tom, sally, harry<P2T

ReplaceAll works like this:

In[11]:= 1 + x2 ê. x Ø tom

:a, b, x, , c> ê. x Ø sally


1
In[12]:=
1+x

So in place of

In[13]:= DSolve@P '@tD ã a P@tD, P@tD, tD

Wagon writes

In[14]:= First@DSolve@P '@tD ã a P@tD, P@tD, tDD

to discard the distracting outer bracket, and


In[15]:= solution = P@tD ê. First@DSolve@P '@tD ã a P@tD, P@tD, tDD

to display the solution of the ODE in question. From

In[16]:= D@solution, tD ã a solution H* a is here not an article, but a factor *L

we confirm that it is in fact a solution.


In our more complicated second example (the coupled system) we write
8psol, qsol< = 8p@tD, q@tD< ê.
First@DSolve@8p '@tD ã a q@tD, q '@tD ã b p@tD<, 8p@tD, q@tD<, tDD
In[17]:=

8D@psol, tD ã a qsol,
D@qsol, tD ã b psol< êê Simplify
In[18]:=

Here ends this digression.

Exponential Population Growth Resumed: the Slope Field Concept

The equation
y '@xD ã f@x, yD

tells us that y[x] describes a curve with the property that when it passes through the point (x,y) it has slope
f[x,y]. If we planted unit vectors with the prescribed slopes on the (x,y)-plane we could obtain y[x] by
simply "threading through" that field of vectors. I illustrate the idea as it relates to the exponential growth
model
P '@tD ã P@tD

In[19]:= Needs@"VectorFieldPlots`"D
4 Laboratory 4A.nb

In[20]:= slopefield = Needs@"VectorFieldPlots`"D; VectorFieldPlots`VectorFieldPlotB

: >, 8t, -2, 2<, 8P, 0, 8<, AspectRatio Ø AutomaticF


1 P
,
2 2
1+P 1+P

We now construct the general solution of the preceding ODE

In[21]:= P@tD ê. First@DSolve@P '@tD ã P@tD, P@tD, tDD

and look to the particular solution that arises from setting C[1] = 1
In[22]:= % ê. C@1D Ø 1

We ask Mathematica to plot that solution


sol = PlotA‰t , 8t, -2, 2<, AspectRatio Ø Automatic,
PlotStyle Ø 8RGBColor@1, 0, 0D, Thickness@0.02D<E
In[23]:=

and to superimpose the two preceding figures

In[24]:= Show@slopefield, solD

This shows quite clearly how the red solution "threads through" the slope field, and it becomes evident to the
eye what the solution that passes through any specified point would look like.
Variants of the idea just illustrated are of very widespread utility, and often help one to grasp the qualitative
essentials of complex situations.

Save.

‡ Limited Population Growth: the "Logistic Model"


Modify the right side of the preceding ODE so as to have
P '@tD ã P@tD H5 - P@tDL
P@0D = 1

From

In[25]:= Plot@P H5 - PL, 8P, 1, 9<D;

we see that the population grows if P < 5, becomes steady at P = 5, diminishes if P > 5. Proceeding

In[26]:= logistic = p '@tD - p@tD H5 - p@tDL

In[27]:= p@tD ê. First@DSolve@8logistic ã 0, p@0D ã 1<, p@tD, tDD

we obtain the particular population curve in which we have a declared interest. We plot it:
Laboratory 4A.nb 5

, 8t, -2, 3<,


5 ‰5 t
In[28]:= logisticpopulation = PlotB
4 + ‰5 t
PlotRange Ø All, PlotStyle Ø 8RGBColor@1, 0, 0D, Thickness@0.01D<,
AxesLabel Ø 8Time, Population<F

Next, we plot the associated slope field

In[29]:= logisticslopefield = Needs@"VectorFieldPlots`"D;

p H5 - pL
>,
1
VectorFieldPlots`VectorFieldPlotB: ,
1 + Hp H5 - pLL 2
1 + Hp H5 - pLL 2

8t, -2, 3<, 8p, 0, 6<, AspectRatio Ø AutomaticF

and superimpose our particular solution on that slope field:

In[30]:= Show@logisticslopefield, logisticpopulationD

Save.

‡ Harmonic Oscillator
The equation of physical interest reads
m x ''@tD = -m w2 x@tD

and in a typical special case (drop the m and set w =3) can be brought to the form
x ''@tD = -32 x@tD

We declare an interest in motion that arises from the initial conditions


x@0D = 0
x '@tD = 1

Here are commands that produce a diagram of a mass attached to a spring:

REMARK: There is much of value to be learned from the following commands (concerning which Abell & Braselton supply explanatory
remarks), but today is not the day.
6 Laboratory 4A.nb

In[31]:= zigzag@8a_, b_<, 8c_, d_<, n_, e_D := ModuleB8length, points, pairs<,
length = d - b;

, 8i, 1, n - 1<F;
i length
points = TableBb +

pairs = TableA9a + e H-1Li , pointsPiT=, 8i, 1, n - 1<E;


n

PrependTo@pairs, 8a, b<D; AppendTo@pairs, 8c, d<D;


Line@pairsDF

In[32]:= typicalposition = 3 ê 4;

Show@Graphics@8zigzag@80, typicalposition<, 80, 2<, 40, 0.05D,


PointSize@0.075D, 8RGBColor@1, 0, 0D, Point@80, typicalposition<D<,
In[34]:=

Line@880.1, 0.75<, 80.3, 0.75<<D, Line@880.2, 0<, 80.2, 0.2<<D,


Arrow@880.2, 0.375<, 80.2, 0.75<<D, Text@"x", 80.2, 0.3<D,
8GrayLevel@0.7D, Rectangle@8-0.5, 2<, 80.5, 2.2<D<<D,
PlotLabel Ø Style@"Simple Harmonic Oscillator",
FontFamily Ø "Times-Bold", FontSize Ø 16D,
Axes Ø Automatic, AxesStyle Ø GrayLevel@0.5D, Ticks Ø None,
PlotRange Ø 88-1, 1<, 8-2, 2.2<<, AspectRatio Ø 1D

We ask Mathematica to solve the equation of motion (which is an ODE of now second order), subject to the
prescribed initial conditions:
harmonicoscillator =
x@tD ê. FirstADSolveA9x ''@tD ã -32 x@tD, x@0D ã 0, x '@0D ã 3=, x@tD, tEE
In[35]:=

There are several ways to display that information; the most obvious is to simply plot it

In[36]:= Plot@harmonicoscillator, 8t, 0, 10<, AxesLabel Ø 8"time", "x"<D

Or we might animate the diagram:


simpleoscillator@t_D :=
Show@Graphics@8zigzag@80, harmonicoscillator<, 80, 2<, 40, 0.05D, PointSize@
In[37]:=

0.075D, 8RGBColor@1, 0, 0D, Point@80, N@harmonicoscillator HtLD<D<,


8GrayLevel@0.7D, Rectangle@8-0.5, 2<, 80.5, 2.2<D<<D,
PlotLabel Ø Style@"Animated Simple Harmonic Oscillator",
FontFamily Ø "Times-Bold", FontSize Ø 16D,
Axes Ø Automatic, AxesStyle Ø GrayLevel@0.5D, Ticks Ø None,
PlotRange Ø 88-1, 1<, 8-2, 2.2<<, AspectRatio Ø 1D

AnimateBsimpleoscillator@tD, :t, 0, >F


2 p 29 2p 1
In[38]:= ,
3 30 3 30

Select any frame, then double click to watch the movie.

Save. Then close this notebook, quit and restart Mathematica, and open Part B.
Physicist's Introduction to Mathematica
Laboratory 4
Part B
‡ Damped Harmonic Oscillator
The standard model of a damped oscillator can be described
m x ''@tD = -2 m b x '@tD - m w2 x@tD

where b is the "damping coefficient." Looking to the general solution (with some not-quite-general initial
conditions)
In[2]:= dampedharmonicoscillator = x@tD ê.
FirstADSolveA9x ''@tD ã -2 b x '@tD - w2 x@tD, x@0D ã 0, x '@0D ã v=, x@tD, tEE

we see that cases with strong damping (b2 > w2 ) are qualitatively distinct from those with weak damping
(b2 < w2 ), and that the critical case b2 = w2 separates the two regimes. To illustrate the point, we~simply to
reduce the number of free variables~set w = v = 3 and proceed

t -b- b2 -32 t -b+ b2 -32


‰ 3 ‰ 3
In[3]:= dampedmotion@t_, b_D := - +
2 b2 - 32 2 b2 - 32

In[4]:= dampedmotion@t, 1 ê 2D

We fuss a bit to bring this result to its most transparently simple form

ExpToTrigB% ‰ 2 F êê Simplify
1
t
In[5]:=

~REMARK: It would have been quicker simply to go back to the beginning, and ask for

In[6]:= x@tD ê.
1
FirstBDSolveB:x ''@tD ã -2 x '@tD - 32 x@tD, x@0D ã 0, x '@0D ã 3>, x@tD, tFF
2

Evidently Mathematica knows spontaneously to do the simplifications that we have to struggle to accomplish~
and plot the resulting function, together with (in blue) the exponentials that modulate it:

F
>, 8t, 0, 10<,
35 t
1
6 SinB 2 1 6 1 6
- t - t - t
In[7]:= PlotB:‰ 2 ,‰ 2 , -‰ 2

35 35 35
PlotStyle Ø 88<, RGBColor@0, 0, 1D, RGBColor@0, 0, 1D<,
PlotRange Ø 8-1, 1<F

To show the effect of increasing b in the underdamped regime we create an animation:


Physicist's Introduction to Mathematica
Laboratory 4
Part C
‡ Damped Pendulum
We look to the illustrative equation
q ''@tD ã -q '@tD - 32 Sin@q@tDD

Mathematica thinks for awhile, then informs us that it is unable to supply an analytical solution

In[2]:= DSolveA9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 3=, q@tD, tE

so we proceed numerically:

In[3]:= NDSolveA9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 3=, q@tD, 8t, 0, 10<E

Or better~we define:
dampedpendulum3000 = q@tD ê. FirstANDSolveA
9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 3=, q@tD, 8t, 0, 10<EE
In[4]:=

In[5]:= PlotBEvaluate@dampedpendulum3000D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-p, p<,

Ticks Ø :Automatic, :-p, - p, 0,


1 1
p, p>>,
2 2
AxesLabel Ø 8Time, Angle<F

g1 = ParametricPlot@
Evaluate@8dampedpendulum3000, D@dampedpendulum3000, tD<D, 8t, 0, 10<,
In[6]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, Automatic<D

In the following series of figures we explore the effect of giving the damped pendulum increased amounts of
initial energy (increasingly higher initial velocities):
dampedpendulum4000 = q@tD ê. FirstANDSolveA
9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 4=, q@tD, 8t, 0, 10<EE
In[7]:=
2 Laboratory 4C.nb

In[8]:= PlotBEvaluate@dampedpendulum4000D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-p, p<,

Ticks Ø :Automatic, :-p, - p, 0,


1 1
p, p>>,
2 2
AxesLabel Ø 8Time, Angle<F

g2 = ParametricPlot@
Evaluate@8dampedpendulum4000, D@dampedpendulum4000, tD<D, 8t, 0, 10<,
In[9]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

dampedpendulum5000 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 5=, q@tD, 8t, 0, 10<EE
In[10]:=

In[11]:= PlotBEvaluate@dampedpendulum5000D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-p, p<,

Ticks Ø :Automatic, :-p, - p, 0,


1 1
p, p>>,
2 2
AxesLabel Ø 8Time, Angle<F

g3 = ParametricPlot@
Evaluate@8dampedpendulum5000, D@dampedpendulum5000, tD<D, 8t, 0, 10<,
In[12]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

dampedpendulum6000 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 6=, q@tD, 8t, 0, 10<EE
In[13]:=

In[14]:= PlotBEvaluate@dampedpendulum6000D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-p, p<,

Ticks Ø :Automatic, :-p, - p, 0,


1 1
p, p>>,
2 2
AxesLabel Ø 8Time, Angle<F
Laboratory 4C.nb 3

g4 = ParametricPlot@
Evaluate@8dampedpendulum6000, D@dampedpendulum6000, tD<D, 8t, 0, 10<,
In[15]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

dampedpendulum7000 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 7=, q@tD, 8t, 0, 10<EE
In[16]:=

In[17]:= PlotBEvaluate@dampedpendulum7000D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-p, p<,

Ticks Ø :Automatic, :-p, - p, 0,


1 1
p, p>>,
2 2
AxesLabel Ø 8Time, Angle<F

g5 = ParametricPlot@
Evaluate@8dampedpendulum7000, D@dampedpendulum7000, tD<D, 8t, 0, 10<,
In[18]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

dampedpendulum8000 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 8=, q@tD, 8t, 0, 10<EE
In[19]:=

In[20]:= PlotBEvaluate@dampedpendulum8000D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-p, p<,

Ticks Ø :Automatic, :-p, - p, 0,


1 1
p, p>>,
2 2
AxesLabel Ø 8Time, Angle<F

Evaluate@8dampedpendulum8000, D@dampedpendulum8000, tD<D, 8t, 0, 10<,


In[21]:= ParametricPlot@

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

dampedpendulum8121 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 8.121=, q@tD, 8t, 0, 15<EE
In[22]:=
4 Laboratory 4C.nb

In[23]:= PlotBEvaluate@dampedpendulum8121D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-p, p<,

Ticks Ø :Automatic, :-p, - p, 0,


1 1
p, p>>,
2 2
AxesLabel Ø 8Time, Angle<F

Note that the pendulum hesitates as it approaches the top of its arc. This shows up in the following figure as a
kink (why?).
g6 = ParametricPlot@
Evaluate@8dampedpendulum8121, D@dampedpendulum8121, tD<D, 8t, 0, 10<,
In[24]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

dampedpendulum8122 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 8.122=, q@tD, 8t, 0, 15<EE
In[25]:=

In[26]:= Plot@Evaluate@dampedpendulum8122D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-0, 3 p<,
Ticks Ø 8Automatic, 80, p, 2 p<<,
AxesLabel Ø 8Time, Angle<D

The pendulum hesitates, then slips over the top, and comes ultimately to rest at q = 2p.
g7 = ParametricPlot@
Evaluate@8dampedpendulum8122, D@dampedpendulum8122, tD<D, 8t, 0, 10<,
In[27]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotStyle Ø RGBColor@0, 0, 1D,
PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

dampedpendulum9000 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 9=, q@tD, 8t, 0, 10<EE
In[28]:=

In[29]:= Plot@Evaluate@dampedpendulum9000D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-0, 3 p<,
Ticks Ø 8Automatic, 80, p, 2 p<<,
AxesLabel Ø 8Time, Angle<,
PlotRange Ø AllD
Laboratory 4C.nb 5

g8 = ParametricPlot@
Evaluate@8dampedpendulum9000, D@dampedpendulum9000, tD<D, 8t, 0, 10<,
In[30]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotStyle Ø RGBColor@0, 0, 1D,
PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

dampedpendulum10000 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 10=, q@tD, 8t, 0, 10<EE
In[31]:=

In[32]:= Plot@Evaluate@dampedpendulum10000D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-0, 3 p<,
Ticks Ø 8Automatic, 80, p, 2 p<<,
AxesLabel Ø 8Time, Angle<,
PlotRange Ø AllD

g9 = ParametricPlot@
Evaluate@8dampedpendulum10000, D@dampedpendulum10000, tD<D, 8t, 0, 10<,
In[33]:=

PlotRange Ø 88-10, 10<, 8-10, 10<<,


PlotStyle Ø RGBColor@0, 0, 1D,
PlotPoints Ø 300,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,
AxesLabel Ø 8q, w<D

Save.

Superimposing all the parametric plots, we obtain

Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,


In[34]:= Show@8g1, g2, g3, g4, g5, g6, g7, g8, g9<,

AxesLabel Ø 8q, w<D;

A little quick experimentation puts us in position to bracket the "twice over" point initial velocity space:
twiceover1 = q@tD ê. FirstANDSolveA
9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 13.89=, q@tD, 8t, 0, 10<EE
In[35]:=

In[36]:= Plot@Evaluate@twiceover1D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-0, 5 p<,
Ticks Ø 8Automatic, 80, p, 2 p, 4 p<<,
AxesLabel Ø 8Time, Angle<,
PlotRange Ø AllD
6 Laboratory 4C.nb

g21 = ParametricPlot@Evaluate@8twiceover1, D@twiceover1, tD<D, 8t, 0, 10<,


PlotRange Ø 88-p, 15<, 8-15, 15<<,
In[37]:=

PlotPoints Ø 300,
Ticks Ø 88-p, 0, p, 2 p, 3 p, 4 p<, None<,
AxesLabel Ø 8q, w<D

twiceover2 = q@tD ê. FirstANDSolveA


9q ''@tD ã -q '@tD - 32 Sin@q@tDD, q@0D ã 0, q '@0D ã 13.90=, q@tD, 8t, 0, 10<EE
In[38]:=

In[39]:= Plot@Evaluate@twiceover2D, 8t, 0, 10<,


PlotStyle Ø RGBColor@1, 0, 0D,
PlotRange Ø 8-0, 5 p<,
Ticks Ø 8Automatic, 80, p, 2 p, 4 p<<,
AxesLabel Ø 8Time, Angle<,
PlotRange Ø AllD

g22 = ParametricPlot@Evaluate@8twiceover2, D@twiceover2, tD<D, 8t, 0, 10<,


PlotRange Ø 88-p, 15<, 8-15, 15<<,
In[40]:=

PlotStyle Ø RGBColor@0, 0, 1D,


PlotPoints Ø 300,
Ticks Ø 88-p, 0, p, 2 p, 3 p, 4 p<, None<,
AxesLabel Ø 8q, w<D

In preparation for the next superimposition of figures we prepare variants of a couple of previous figures
(extended range), which we paint gray:
G1 = ParametricPlot@
Evaluate@8dampedpendulum8121, D@dampedpendulum8121, tD<D, 8t, 0, 10<,
In[41]:=

PlotRange Ø 88-p, 15<, 8-15, 15<<,


PlotStyle Ø GrayLevel@.6D,
PlotPoints Ø 300,
Ticks Ø 88-p, 0, p, 2 p, 3 p, 4 p<, None<,
AxesLabel Ø 8q, w<D

G2 = ParametricPlot@
Evaluate@8dampedpendulum8122, D@dampedpendulum8122, tD<D, 8t, 0, 10<,
In[42]:=

PlotRange Ø 88-p, 15<, 8-15, 15<<,


PlotStyle Ø GrayLevel@.6D,
PlotPoints Ø 300,
Ticks Ø 88-p, 0, p, 2 p, 3 p, 4 p<, None<,
AxesLabel Ø 8q, w<D

Now the final superpositon:

In[43]:= Show@8G1, G2, g21, g22<, Ticks Ø NoneD

There are yet other ways to represent the results produced by DSolve[ ] and NDSolve[
]commands.

Save.
Laboratory 4C.nb 7

Save.

This is amusing stuff, but raises a philosophical point:


It is gratifying to find that our animations "reproduce the real world," but to the extent that they do so they teach
us little more than we would learn by simply looking at the world itself. Previous modes of graphical display~
though more "diagramatic," and though they may require some interpretive practice~speak more
clearly/informatively to what is going on, teach us how to look at the real world. This much is, in any event
clear: When you have solved a differential equation your work is typically only half done; you have yet to
devise the best way, in the particular instance, to make your result intelligible. Strings of data~produced
maybe this way

ê. t Ø k, 8k, 0, 10, .5<F êê TableForm


dampedpendulum8122
In[46]:= TableB
2p

may be all you need in some few cases, but graphical display is often your most powerful resource. It is a
resource which Mathematica permits you to manage with unprecedented power and efficiency.

Save.

‡ Quantum Oscillator
Near the heart of this important subject lies a particular instance
—2 1
- ∂x,x y@xD + m w2 x2 y@xD ã energy y@xD
2m 2

(— is typed ÂhbÂ) of the time-independent Schrodinger equation, which we recognize to be a 2nd-order linear
ODE with variable coefficients. It can, with a little massaging, be brought to the form (see David Griffiths,
Introduction to Quantum Mechanics, p. 37)
f ''@xD - x2 f@xD + K f@xD ã 0

Fundamental principles of quantum mechanics inform us that we have physical interest only in those solutions
y[x] which are normalizable/normalized, in the sense that

‡ y@xD „ x = 1

2

It emerges that this condition can be fulfilled if and only if energy is assigned one or another of a discrete set
of special values (energy eigenvalues).

Digression

Physical arguments typically begin with "a little massaging" intended to clear the deck of distracting constants
and parameters; i.e., to absorb those into the definition of a population of dimensionless variables. Don't know
about you, but I find such "massaging" to be a ticklish and distracting business I would as happily do without.
Authors are (like Griffiths, in this instance) usually content to simply report the final result of their tinkering. I
digress to illustrate how Mathematica might be pressed into such service.
Our plan is to write
8 Laboratory 4C.nb

Our plan is to write


y@xD = f@xD with x = a x

and to assign an "optimal" value to a . Our original Schrodinger equation becomes


—2 1
In[47]:= - D@f@a xD, x, xD + m w2 x2 f@a xD - energy f@a xD
2m 2

We introduce the x variable


—2 a2 f££ @x aD
ê. x Ø x ê a
1
In[48]:= -energy f@x aD + m x2 w2 f@x aD -
2 2m

and look for the optimal a :


m w2 —2 a2
In[49]:= SolveB == , aF
2 a2 2m

Adopting the last of those possibilities, we have


—2 a2 f££ @xD
ê. a -> m wê—
m x2 w2 f@xD
In[50]:= -energy f@xD + -
2 a2 2m

Finally

% êê Simplify
2
In[51]:=
—w

leads us to define
2 energy
K=
hw

We have at this point recovered the equation reported by Griffiths. Here ends this digression.

Main Discussion~Resumed

The literature supplies many ways to approach


f ''@xD - x2 f@xD + K f@xD ã 0

analytically. The resources of Mathematica suggest, however, the following non-standard approach, which has
the merit that it does not presume deep knowledge of classical analysis.
We begin by asking what (of an analytical nature) Mathematica has to say in a typical case; we set K = 1, adopt
some reasonable-seeming conditions at x = 0 and find…
In[52]:= Clear@x, fD

Mathematica is about to enter a series of complaints. Just hit OK when given the opportunity, not to worry.
Laboratory 4C.nb 9

In[53]:= DSolveA9f ''@xD - x2 f@xD + 1 f@xD ã 0, f@0D ã 1, f '@0D ã 0=, f@xD, xE

We get a gaussian as expected. We can also proceed numerically:


numericaltest = f@xD ê. FirstANDSolveA
9f ''@xD - x2 f@xD + 1 f@xD ã 0, f@0D ã 1, f '@0D ã 0=, f@xD, 8x, -10, 10<EE
In[54]:=

In[55]:= Plot@Evaluate@numericaltestD, 8x, -4, 4<D

We note belatedly that the condition f'[0]ã0 has forced f[x] to be an even function. It looks like we may
have caught a fish (a normalizable solution) with our first cast, but more careful scrutiny…
In[56]:= Plot@Evaluate@numericaltestD, 8x, -5.5, 5.5<D

…casts that conclusion into doubt; we confront the question: Are the tails real or numerical artifacts? The
following result
In[57]:= NIntegrate@numericaltest, 8x, -10, 10<D

dramatizes the situation, but leaves the question unanswered.


There are a lot of K-values to try. We need to fish in some more systematic way. We elect to use the animation
resource to trawl for even normalizable solutions:
In[58]:= AnimateAPlotAEvaluateAf@xD ê. FirstA
NDSolveA9f ''@xD - x2 f@xD + K f@xD ã 0, f@0D ã 1, f '@0D ã 0=, f@xD,
8x, -10, 10<EEE, 8x, -6, 6<, PlotRange Ø 8-2, 1.5<E, 8K, 0, 24, 1 ê 2<E

Simple adjustment of the initial data permits us to trawl for odd solutions:

In[59]:= AnimateAPlotAEvaluateAf@xD ê. FirstA


NDSolveA9f ''@xD - x2 f@xD + K f@xD ã 0, f@0D ã 0, f '@0D ã 1=, f@xD,
8x, -10, 10<EEE, 8x, -6, 6<, PlotRange Ø 8-2, 1.5<E, 8K, 0, 24, 1 ê 2<E

These movies suggest that we pick up normalizable solutions at the "whip-through" values of K, which in the
even case appear to occur at K=1, 5, 9, 13, … and in the odd case to occur at K=3, 7, 11, 15, … We are led by
this observation to look again to the complainy output
In[60]:= DSolveA9f ''@xD - x2 f@xD + 1 f@xD ã 0, f@0D ã 1, f '@0D ã 0=, f@xD, xE

Note the occurance of C[1] and C[2]; Mathematica has for some reason elected to ignore our initial data
statements. The following figures

x J 1x N
x2
-

, 8x, -6, 6<FH*We have set C@1D=1, C@2D=0*L


‰ 2

In[61]:= PlotB
2
x2
- p Erfi@xD
‰ x
, 8x, -6, 6<F
2
2x
In[62]:= PlotB
2
H*We have set C@1D=0, C@2D=1*L

lead us~speculatively, experimentally~to abandon the Erfi[x] term.


10 Laboratory 4C.nb

lead us~speculatively, experimentally~to abandon the Erfi[x] term.


In[63]:= ? Erfi

Defining

x J 1x N
x2
-

f1 @x_D :=
‰ 2

In[64]:=
2

we find that this function does satisfy the ODE in question

In[65]:= f1 ''@xD - x2 f1 @xD + 1 f1 @xD ã 0 êê Simplify

and that it is normalizable:

‡ f1 @xD „ x

2
In[66]:=

Enlarging upon this experience, we omit the initial data specifications (seems to be Mathematica's preference)

In[67]:= DSolveA9f ''@xD - x2 f@xD + 3 f@xD ã 0=, f@xD, xE

In[68]:= DSolveA9f ''@xD - x2 f@xD + 5 f@xD ã 0=, f@xD, xE

In[69]:= DSolveA9f ''@xD - x2 f@xD + 7 f@xD ã 0=, f@xD, xE

In[70]:= DSolveA9f ''@xD - x2 f@xD + 9 f@xD ã 0=, f@xD, xE

and in each instance set C[1] = 1, C[2] = 0 to obtain

f3 @x_D :=
x2
-
‰ 2 x
In[71]:=
2

f5 @x_D :=
1 -
x2 1
‰ 2 x 1- x
2 2 x2

x I- 32 + x2 M
x2

f7 @x_D :=
-
‰ 2

f9 @x_D :=
1 -
x2 3 3
‰ 2 x 1+ - x3
2 4 x4 x2

This done, we find that


f3 ''@xD - x2 f3 @xD + 3 f3 @xD ã0 êê
f5 @xD + 5 f5 @xD êê
In[75]:= Simplify
f5 ''@xD - x2 ã0
f7 @xD + 7 f7 @xD êê
Simplify
f7 ''@xD - x2 ã0
f9 @xD + 9 f9 @xD êê
Simplify
f9 ''@xD - x2 ã0 Simplify

and that
Laboratory 4C.nb 11

‡ f3 @xD „ x

2
In[79]:=

‡ f5 @xD „ x

2

‡ f7 @xD „ x

2

‡ f9 @xD „ x

2

So we have now in hand these normalized oscillator eigenfunctions:

Y1 @x_D := f1 @xD ì
p
In[83]:=
2

Y3 @x_D := f3 @xD ì
p
4

Y5 @x_D := f5 @xD ì
p
4

Y7 @x_D := f7 @xD ì
3 p
8

Y9 @x_D := f9 @xD ì
3 p
4

That they are normalized is demonstrated by calculations of the form

‡ Y3 @xD „ x

2
In[88]:=

‡ Y5 @xD „ x

2

‡ Y7 @xD „ x

2

while calculations of the form


12 Laboratory 4C.nb

‡ Y3 @xD Y5 @xD „ x

In[91]:=

‡ Y3 @xD Y7 @xD „ x

‡ Y5 @xD Y7 @xD „ x

demonstrate that they are also "orthogonal" (as quantum mechanical first principles require).
With a bit more work we could (and, if this were a quantum course, would) obtain all the oscillator
eigenfunctions/eigenvalues. For the moment, however, we must be content with this important computational
conclusion: The tails, on present evidence, can be dismissed as numerical artifacts. The moral is clear: One
must be careful not to be led astray by numerical artifacts.

Save.
Physicist's Introduction to Mathematica
Laboratory 4
Part D
‡ Ballistics
Consider the motion of a thrown mass point; immediately
8x@tD, y@tD< ê. First@DSolve@8x ''@tD ã 0, y ''@tD ã -g, x@0D ã 0,
y@0D ã 0, x '@0D ã v Cos@qD, y '@0D ã v Sin@qD<, 8x@tD, y@tD<, tDD
In[2]:=

This, of course, is physics learned in the second week of an introductory course, and if we make a movie
(various launch angles, constant launch speed)…
In[3]:= x@t_, v_, q_D := t v Cos@qD

I-g t2 + 2 t v Sin@qDM
1
y@t_, v_, q_, g_D :=
2

p ê 2F, yBt, 8, p ê 2, 4F>,


k k
In[5]:= undampedflight = TableBParametricPlotB:xBt, 8,

8t, 0, 4<, PlotRange Ø 880, 17<, 80, 8.5<<,


20 20

Ticks Ø None,
AspectRatio Ø AutomaticF, 8k, 0, 19<F;

…and superimpose the frames

In[6]:= Show@undampedflightD

…we obtain an image which has been engraved in physics books since early in the 1600s.

Save.

But the following steps culminate in a variant of that same familiar figure which contains an element of sur-
prise. First we draw the arcs traced by particles which are launched (all with the same speed) in various
directions

F, yBt, 8, k
2p 2p
In[7]:= arctable = AnimateBParametricPlotB:xBt, 8, k , 4F>,

8t, 0, 4<, PlotRange Ø 88-35, 35<, 8-70, 10<<,


30 30

Ticks Ø None,
AspectRatio Ø AutomaticF, 8k, 0, 29<F
2 Laboratory 4D.nb

F, yBt, 8, k
2p 2p
In[67]:= arctable = TableBParametricPlotB:xBt, 8, k , 4F>,

8t, 0, 4<, PlotRange Ø 88-35, 35<, 8-70, 10<<,


30 30

Ticks Ø None,
AspectRatio Ø AutomaticF, 8k, 0, 29<F;

Next we construct a representation of where that population of particles resides at time t = 4:

F, yB4, 8, k , 4F>F, 8k, 0, 29<F;


2p 2p
In[8]:= pointtable = TableBPointB:xB4, 8, k
30 30

In[9]:= Show@Graphics@8PointSize@0.02D, RGBColor@1, 0, 0D, pointtable<D,


PlotRange Ø All,
AspectRatio Ø AutomaticD

and finally we superimpose those figures:

In[10]:= Show@arctable, Graphics@8PointSize@0.02D, RGBColor@1, 0, 0D, pointtable<DD

The circle is the surprise…though such circles are seen every 4th of July, and become quite unsurprising when
you consider how the particle motion would appear to an observer falling from the explosion point.
We are in position now to do also things not commonly done in an introductory course. For example: let us
suppose a thrown projectile experiences a drag force of the form
drag vector = -Hdrag coefficientL Hvelocity vectorL

We ask Mathematica to solve

In[11]:= 8X@tD, Y@tD< ê.


First@DSolve@8X ''@tD ã -b X '@tD, Y ''@tD ã -b Y '@tD - g, X@0D ã 0, Y@0D ã 0,
X '@0D ã v Cos@qD, Y '@0D ã v Sin@qD<, 8X@tD, Y@tD<, tDD

To discover what this is telling us we proceed graphically, exactly as before; we define


‰-b t I-1 + ‰b t M v Cos@qD
In[12]:= X@t_, v_, q_, b_D :=
b
Y@t_, v_, q_, g_, b_D :=

I‰-b t Ig - ‰b t g + b ‰b t g t + b v Sin@qD - b ‰b t v Sin@qDMM


1
-
2
b

We assign former values to v and g, and (after some preliminary experimentation) set b=3/10; we are led thus
to the following graphics:
Laboratory 4D.nb 3

In[14]:= dampedflight =

p ê 2, F, YBt, 8, p ê 2, 4, F>,
k 3 k 3
TableBParametricPlotB:XBt, 8,

8t, 0, 4<, PlotRange Ø 880, 17<, 80, 8.5<<,


20 10 20 10

Ticks Ø None,
AspectRatio Ø Automatic,
PlotStyle Ø RGBColor@0, 0, 1DF, 8k, 0, 19<F;

In[15]:= Show@dampedflightD

In[16]:= Show@undampedflight, dampedflightD

‡ Planetary Motion
So well known is this problem that, without physical preamble, we proceed

In[17]:= Clear@x, y, a, bD

>,
x@tD y@tD
DSolveB:x ''@tD ã - , y ''@tD ã -
Ix@tD + y@tD M 2 Ix@tD + y@tD M 2
In[18]:=
3 3
2 2 2 2

8x@tD, y@tD<, tF

and find that Mathematica is seems unwilling to provide a general solution in analytical closed form. So we
proceed numerically (which obliges us to specify some experimental initial conditions):
x@tD y@tD
orbit1 = NDSolveB:x ''@tD ã - , y ''@tD ã - ,
Ix@tD + y@tD M 2 Ix@tD + y@tD M 2
In[19]:=
3 3
2 2 2 2

x@0D ã 1, y@0D ã 0, x '@0D ã 0, y '@0D ã .5>, 8x@tD, y@tD<, 8t, 0, 3<F

In[20]:= firstorbit = ParametricPlot@Evaluate@8x@tD, y@tD< ê. orbit1D, 8t, 0, 2<,


PlotRange Ø All,
AspectRatio Ø Automatic,
PlotStyle Ø RGBColor@0, 0, 1DD

x@tD y@tD
orbit2 = NDSolveB:x ''@tD ã - , y ''@tD ã - ,
Ix@tD + y@tD M Ix@tD + y@tD M
In[21]:=
3 3
2 2 2 2 2 2

x@0D ã 1, y@0D ã 0, x '@0D ã 0, y '@0D ã .6>, 8x@tD, y@tD<, 8t, 0, 3<F

In[22]:= secondorbit = ParametricPlot@Evaluate@8x@tD, y@tD< ê. orbit2D, 8t, 0, 2<,


PlotRange Ø All,
AspectRatio Ø Automatic,
PlotStyle Ø RGBColor@1, 0, 0DD
4 Laboratory 4D.nb

x@tD y@tD
orbit3 = NDSolveB:x ''@tD ã - , y ''@tD ã - ,
Ix@tD + y@tD M 2 Ix@tD + y@tD M 2
In[23]:=
3 3
2 2 2 2

x@0D ã 1, y@0D ã 0, x '@0D ã 0, y '@0D ã .4>, 8x@tD, y@tD<, 8t, 0, 3<F

In[24]:= thirdorbit = ParametricPlot@Evaluate@8x@tD, y@tD< ê. orbit3D, 8t, 0, 2<,


PlotRange Ø All,
AspectRatio Ø AutomaticD

In[25]:= Show@firstorbit, secondorbit, thirdorbitD;

One could write a book about this system (Newton did, NASA has, and so have a million others), but I will
make only one further observation~illustrative of how easy it is to go exploring with the bright assistance of
Mathematica. Let us modify~slightly~the force law:
In[26]:= superperturbedorbit =
x@tD y@tD

Ix@tD2 + y@tD2 M Ix@tD2 + y@tD2 M


NDSolveB:x ''@tD ã - , y ''@tD ã - ,
1.51 1.51

x@0D ã 1, y@0D ã 0, x '@0D ã 0, y '@0D ã .4>, 8x@tD, y@tD<, 8t, 0, 10<F

In[27]:= ParametricPlot@Evaluate@8x@tD, y@tD< ê. superperturbedorbitD, 8t, 0, 9<,


PlotRange Ø All,
AspectRatio Ø AutomaticD

Compare that non-reentrant orbit with the following one:

In[28]:= subperturbedorbit =
x@tD y@tD

Ix@tD + y@tD M Ix@tD + y@tD M


NDSolveB:x ''@tD ã - , y ''@tD ã - ,
2 2 1.49 2 2 1.49

x@0D ã 1, y@0D ã 0, x '@0D ã 0, y '@0D ã .4>, 8x@tD, y@tD<, 8t, 0, 10<F

In[29]:= ParametricPlot@Evaluate@8x@tD, y@tD< ê. subperturbedorbitD, 8t, 0, 9<,


PlotRange Ø All,
AspectRatio Ø AutomaticD

The precession is prograde in the former case, retrograde in the latter. The following experiment

In[30]:= barelysuperperturbedorbit =
x@tD y@tD

Ix@tD2 + y@tD M Ix@tD2 + y@tD2 M


NDSolveB:x ''@tD ã - , y ''@tD ã - ,
2 1.5015 1.5015

x@0D ã 1, y@0D ã 0, x '@0D ã 0, y '@0D ã .4>, 8x@tD, y@tD<, 8t, 0, 15<F

Evaluate@8x@tD, y@tD< ê. barelysuperperturbedorbitD, 8t, 0, 15<,


In[31]:= ParametricPlot@

PlotRange Ø All,
AspectRatio Ø AutomaticD

suggests that panetary data~since it extends back for millennia, and is taken with instruments of very high
accuracy~can be used to establish that Newton's 2nd-power law is very accurately a 2nd-power law, else orbits
would precess enough to swamp out the tiny general relativistic effect discovered by Einstein.
Laboratory 4D.nb 5

suggests that panetary data~since it extends back for millennia, and is taken with instruments of very high
accuracy~can be used to establish that Newton's 2nd-power law is very accurately a 2nd-power law, else orbits
would precess enough to swamp out the tiny general relativistic effect discovered by Einstein.

‡ Endpoint Conditions
We are in the habit of specifying orbits by stipulating initial conditions, but in advanced mechanics one devel-
ops (in connection with the way certain "variational principles" are phrased) an interest in the orbits which
conform to stipulated endpoint conditions; indeed, a pitcher has something resembling endpoint conditions in
mind when he pitches the ball. Here I want only to point out that Mathematica takes endpoint conditions in easy
stride.
Look, by way of illustration, to the familiar harmonic oscillator:

In[32]:= DSolveA9x ''@tD ã -w2 x@tD, x@0D ã a, x@TD ã b=, x@tD, tE

We resort once again to graphical techniques to display what we have accomplished:

In[33]:= x@t_, T_, a_, b_, w_D := a Cos@t wD + H-a Cot@T wD + b Csc@T wDL Sin@t wD

In[34]:= endpoints = List@Point@80, .5<D, Point@81.75, -1<DD

In[35]:= connectingorbits = PlotB:


7
xBt, , .5, -1, 2 pF,
4
7
xBt, , .5, -1, 2 p + .1F,
4
7
xBt, , .5, -1, 2 p + .2F,
4
7
xBt, , .5, -1, 2 p + .3F,
4

, .5, -1, 2 p + .4F>, :t, 0, >, PlotRange Ø 88-.2, 2<, 8-2, 2<<,
7 7
xBt,
4 4
Ticks Ø 881.75<, 8.5<<, AxesLabel Ø 8time, displacement<F;

In[36]:= Show@connectingorbits,
Graphics@8PointSize@0.03D, RGBColor@1, 0, 0D, endpoints<DD

Save.
Physicist's Introduction to Mathematica
Physics 200 Physics 50 Lab Revised for V6.0
Fall Semester 2000 Spring Semester 2006 Summer 2007
Nicholas Wheeler John Boccio John Boccio
REED COLLEGE Swarthmore College Swarthmore College
V4.0 Revised for V5.0

Laboratory 5
Part A

Partial Differential Equations

When you ask Mathematica to solve an ordinary DE~say


I1 - x2 M y ''@xD - x y '@xD + n2 y@xD ã 0

or
x ''@tD + b x '@tD + w2 x@tD ã DiracDelta@tD

~it has powerful resources to draw upon (the "Kovacic algorithm," "Bocharov techniques," etc.…with alto-
gether use about 300 pages of Mathematica code and 200 pages of C code), and often has immediate things to
say:
In[2]:= DSolveAI1 - x2 M y ''@xD - x y '@xD + n2 y@xD ã 0, y@xD, xE

In[3]:= DSolveAx ''@tD + b x '@tD + w2 x@tD ã DiracDelta@tD, x@tD, tE

And when those techniques fail one can proceed numerically, with NDSolve.
Partial differential equations (PDEs) are, however, a different story. Though

In[4]:= ? DSolve

does speak of PDEs, and Mathematica is by no means powerless in this area, it often responds unhelpfully.
Look, for example, to the one-dimensional heat equation
∂t u@x, tD ã a ∂x,x u@x, tD

concerning which we are told that

In[5]:= DSolve@∂t u@x, tD ã a ∂x,x u@x, tD, u@x, tD, 8x, t<D

But if we proceed as suggested


2 Laboratory 5A.nb

But if we proceed as suggested


Doubtless there is much about this subject I myself have yet to learn, but it has been my experience that if I~
confronted with a PDE~have a plan of attack, then Mathematica will assist me in management of the details.
But Mathematica will not usually suggest a plan of attack; for those I must read books. PDE's are not nearly so
"cut and dried" as ODEs. Let us look to an illustrative instance:

‡ Waves on a String
The one dimensional wave equation reads
c2 ∂x,x u@x, tD - ∂t,t u@x, tD ã 0

Proceeding
In[8]:= DSolveAc2 ∂x,x u@x, tD - ∂t,t u@x, tD ã 0, u@x, tD, 8x, t<E

Mathematica informs us that we obtain a solution when we write

F + GBt - F H*Any F@D, any G@D*L


x x
In[9]:= u@x, tD := FBt +
c c

We learned this already from class work, but check it out:

In[10]:= c2 ∂x,x u@x, tD - ∂t,t u@x, tD ã 0

In[11]:= Simplify@%D

In[12]:= Clear@u, f, gD

Suppose we sought a solution with the property that


u@x, 0D = f@xD H*any f@D*L
Limit@∂t u@x, tD, t Ø 0D = g@xD H*any g@D*L

The command

In[13]:= DSolveA9c2 ∂x,x u@x, tD - ∂t,t u@x, tD ã 0,


u@x, 0D == f@xD,
Limit@∂t u@x, tD, t Ø 0D == g@xD=, u@x, tD, 8x, t<E

got us nowhere. Yet we learn from books that an elegant solution of that initial value problem was known
already (by about 1750) to d'Alembert:

Hf@x + c tD + f@x - c tDL + ‡


1 1 x+c t
In[14]:= u@x, tD = g@xD „ x
2 2c x-c t

And Mathematica, once pointed in the right direction, is quick to agree with d'Alembert:

In[15]:= c2 ∂x,x u@x, tD - ∂t,t u@x, tD ã 0

In[16]:= Simplify@%D
Laboratory 5A.nb 3

In[17]:= u@x, tD ê. t Ø 0

In[18]:= ∂t u@x, tD ê. t Ø 0

It is when we decide to use these results to explore particular cases that Mathematica comes again most vividly
into its own:

First Example

F
x
In[19]:= u@x, tD := SinBt -
c

In[20]:= c2 ∂x,x u@x, tD - ∂t,t u@x, tD ã 0

In[21]:= j@x, tD := u@x, tD ê. c Ø 1

In[22]:= j@x, tD

If we wanted to display that result on the printed page we might proceed


Plot3D@Sin@t - xD, 8x, -2 p, 2 p<, 8t, 0, 6<, PlotPoints Ø 30,
AxesLabel Ø 8FontForm@"position", 8"Helvetica-Bold", 12<D,
In[23]:=

FontForm@"time", 8"Helvetica-Bold", 12<D,


FontForm@"amplitude", 8"Helvetica-Bold", 12<D<,
Ticks Ø 88-2 p, -p, 0, p, 2 p<, Automatic, None<D;

but if we planned to speak about it in a modern lecture hall we would probably find it more effective to make a
movie:

- xF, 8x, -2 p, 2 p<F;, 8k, 0, 20<F;


6
In[24]:= TableBPlotBSinBk
20

Watch the movie, then delete the filmstrip and Save.

Second Example

F+ F
x 1 x
In[25]:= u@x, tD := SinBt - CosB3 t +
c 3 c

In[26]:= c2 ∂x,x u@x, tD - ∂t,t u@x, tD ã 0

In[27]:= Simplify@%D

In[28]:= j@x, tD := u@x, tD ê. c Ø 1

In[29]:= j@x, tD

The static 3D figure is now almost too complicated to be informative:


4 Laboratory 5A.nb

Plot3D@Sin@t - xD, 8x, -2 p, 2 p<, 8t, 0, 6<, PlotPoints Ø 30,


AxesLabel Ø 8"position", "time", "amplitude"<,
In[30]:=

Ticks Ø 88-2 p, -p, 0, p, 2 p<, Automatic, None<D

Animation clarifies the meaning of the figure:

+ x F + SinBk
1 6 6
In[31]:= AnimateBPlotB CosB3 k - xF,
3 40 40
8x, -2 p, 2 p<, PlotRange Ø 8-2, 2<F, 8k, 0, 40<F;

NOTICE that in both of the preceding figures I have increased the resolution (number of PlotPoints, number of frames) to accommo-
date the increased density of detail.

Third Example: d'Alembert's Solution

d'Alembert speaks of the wave form that evolves from prescribed initial data (a "thrown wave," if you will…the
term borrowed from what we prescribe when we throw a rock). Our first example
In[32]:= u@x, tD := Sin@t - xD

entails

In[33]:= f@xD := Limit@u@x, tD, t Ø 0D


g@xD := Limit@∂t u@x, tD, t Ø 0D

In[35]:= f@xD
g@xD

d'Alembert would use that data to construct

H-Sin@x + tD - Sin@x - tDL + ‡


1 1 x+ t
In[37]:= Cos@xD „ x
2 2 x- t

In[38]:= Simplify@%D

which does indeed reproduce our known (and previously plotted) starting point. Look to this more interesting
case:

Gaussian Initial Profile, String Initially at Rest


2 ë4
In[39]:= f@xD := ‰-x
g@xD := 0

d'Alembert asserts that

K‰ O
1 -Hx+tL2 í 4 -Hx-tL2 í 4
In[41]:= u@x, tD := +‰
2

In[42]:= ∂x,x u@x, tD - ∂t,t u@x, tD ã 0

In[43]:= Simplify@%D
Laboratory 5A.nb 5

K‰ O, 8x, -2 p, 2 p<, 8t, 0, 6<, PlotPoints Ø 50,


1 -Hx+tL2 í 4 -Hx-tL2 í 4
In[44]:= Plot3DB +‰

AxesLabel Ø 8"position", "time", "amplitude"<,


2

Ticks Ø 88-2 p, -p, 0, p, 2 p<, Automatic, None<F

N ì4 N ì4
, 8x, -2 p, 2 p<,
2 2
1 -Jx+k
6
-Jx-k
6

In[45]:= AnimateBPlotB ‰ 30
+‰ 30

2
PlotRange Ø 80, 1<, Ticks Ø 8Automatic, 80.5, 1<<F, 8k, 0, 30<F

Separation of Variables

This~classically~has for 200 years been the most powerful technique for solving PDEs (the modern alterna-
tive is to proceed numerically from start to finish); it remains so today, and is destined to remain so forever.
When it works it is beautiful, but (for reasons we will be at pains to understand) it works only in favorable
cases. The effect of the method is to reduce the PDE to a set of ODEs which are coupled only through certain
shared "separation constants"… the point being that ODEs do yield to a battery of powerful techniques. I
discuss the method as it relates to the physics of a vibrating membrane~specifically, a circular drumhead. The
PDE of interest, therefore, is the 2-dimensional wave equation, which in Cartesian coordinates stipulates that
In[46]:= c2 HD@j@x, y, tD, 8x, 2<D + D@j@x, y, tD, 8y, 2<DL - D@j@x, y, tD, 8t, 2<D

vanishes.

‡ Separation with Respect to the Time Variable


We assume j[x,y,t] to have the factored design
j@x, y, tD = u@x, yD * f@tD

The left side of the wave equation then becomes

In[47]:= c2 HD@u@x, yD f@tD, 8x, 2<D + D@u@x, yD f@tD, 8y, 2<DL - D@u@x, yD f@tD, 8t, 2<D

Division by u[x,y]f[t]gives
-u@x, yD f££ @tD c2 f@tD uH0,2L @x, yD c2 f@tD uH2,0L @x, yD
In[48]:= + +
u@x, yD f@tD u@x, yD f@tD u@x, yD f@tD

which can vanish if and only if these two statements are separately true:
f££ @tD
- = constant
f@tD
6 Laboratory 5A.nb

uH0,2L @x, yD uH2,0L @x, yD constant


+ + =0
u@x, yD u@x, yD c2

We are interested in the oscillatory solutions of the first equation (which is to say: not interested in exponential
explosion/death), so we enforce constant > 0 by writing
constant = w2

Our original PDE has thus "separated" into an ODE


f££ @tD + w2 f@tD = 0

and a PDE involving only 2 (instead of the original 3) independent variables:

uH0,2L @x, yD + uH2,0L @x, yD +


w2
u@x, yD = 0
c2

The former gives

In[49]:= DSolveAf££ @tD + w2 f@tD ã 0, f@tD, tE

while the latter can be written


uH0,2L @x, yD + uH2,0L @x, yD + k2 u@x, yD = 0

(this is the 2-dimensional Helmholtz equation) with


w2
k2 =
c2

which we will find it most convenient to express


w@k_D := c k

‡ Polar Separation of the Helmholtz Equation


The objective now is to resolve Helmholtz' PDE into a pair of ODEs, and to do so in a way that respects the
symmetry of our circular drumhead~that so we can express the physical circumstance that the boundary of the
drumhead has been "clamped." To that end, we introduce polar coordinates in the usual way
x = r Cos@qD
y = r Sin@qD

and write
u@x, yD = F@r@x, yD, q@x, yDD

with

In[50]:= r@x_, y_D := x2 + y2


q@x_, y_D := ArcTan@x, yD

In[52]:= ? ArcTan

The Laplacian of u[x,y] is by these adjustments brought to the form


Laboratory 5A.nb 7

The Laplacian of u[x,y] is by these adjustments brought to the form


D@F@r@x, yD, q@x, yDD, 8x, 2<D +
D@F@r@x, yD, q@x, yDD, 8y, 2<D
In[53]:=

In[54]:= Simplify@%D

In[55]:= % ê. 9x2 + y2 Ø r2 , ArcTan@x, yD Ø q=

In[56]:= Simplify@%, r > 0D

Short Digression

The command

In[57]:= SimplifyB r2 F

does nothing because Mathematica considers the result to depend on whether r is positive or negative, and does
not know which we intend. So we tell it:

In[58]:= SimplifyB r2 , r > 0F

In the alternative case we would have obtained

In[59]:= SimplifyB r2 , r < 0F

Now we return to the main discussion.

We next make again the characteristic "separation assumption" that


F@r, qD = R@rD * A@qD

Our former Helmholz equation


uH0,2L @x, yD + uH2,0L @x, yD + k2 u@x, yD = 0

is brought thus to the form of a requirement that

In[60]:= H R@rD A ''@qD + r HR '@rD A@qD + r R ''@rD A@qDLL + k2 r2 R@rD A@qD

vanish. Division by R[r]A[q] gives


R@rD A££ @qD r A@qD HR£ @rD + r R££ @rDL k2 r2 R@rD A@qD
In[61]:= + +
R@rD A@qD R@rD A@qD R@rD A@qD

~the vanishing of which requires that


A££ @qD
= constant
A@qD
8 Laboratory 5A.nb

r HR£ @rD + r R££ @rDL


k2 r2 + + constant = 0
R@rD

This is a pair of ODEs, joined at the hip through the "separation constant." We require on physical grounds that
A@q + 2 pD = A@qD

This requires that we look only to the periodic solutions of the ODE
A ''@qD - constant * A@qD = 0

So we set
constant = -m2

and our final separated equations read


f ''@tD + c2 k2 f@tD = 0

A ''@qD + m2 A@qD = 0

r HR£ @rD + r R££ @rDL + Ik2 r2 - m2 M R@rD = 0

We have made two separations, and our final equations contain therefore two separation constants: k and m .
This complete my illustrative discussion of how one achieves separation (reduction of a PDE to a set of
constant-coupled ODEs), but there is more to be said~both mathematically and physically: From
In[62]:= DSolveAA ''@qD + m2 A@qD ã 0, A@qD, qE

we learn that m must be an integer: m=0,1,2,… Next we look to


In[63]:= DSolveAr2 R ''@rD + r R '@rD + Ik2 r2 - 12 M R@rD ã 0, R@rD, rE

and find that we have been led to Bessel functions:

In[64]:= ? BesselJ

In[65]:= ? BesselY

On the following graphical evidence

In[66]:= Plot@BesselJ@0, xD, 8x, 0, 10<D

In[67]:= Plot@BesselJ@1, xD, 8x, 0, 10<D

In[68]:= Plot@BesselY@1, xD, 8x, 0, 10<D

we are prepared on physical grounds (ignorant though we presently are of the theory of Bessel functions) to
discard the BesselY solutions. We are left with solutions of the forms
j1 @r_, q_, t_, k_, m_D := BesselJ@m, k rD Cos@m qD Cos@c k tD
j2 @r_, q_, t_, k_, m_D := BesselJ@m, k rD Sin@m qD Cos@c k tD
In[69]:=

j3 @r_, q_, t_, k_, m_D := BesselJ@m, k rD Cos@m qD Sin@c k tD


j4 @r_, q_, t_, k_, m_D := BesselJ@m, k rD Sin@m qD Sin@c k tD

But we require~clamped boundary condition~that


Laboratory 5A.nb 9

But we require~clamped boundary condition~that


j@a, q, tD = 0 H* all q, all t; a is radius of drum *L

We acquire thus an interest in the roots of the BesselJ functions. Looking back to the graph produced by the
command Plot[BesselJ[0,x],{x,0,10}]; we find
List@8"First root of J0 ", FindRoot@BesselJ@0, xD ã 0, 8x, 2<D<,
8"Second root of J0 ", FindRoot@BesselJ@0, xD ã 0, 8x, 6<D<,
In[73]:=

8"Third root of J0 ", FindRoot@BesselJ@0, xD ã 0, 8x, 9<D<D êê TableForm

List@8"First root of J1 ", FindRoot@BesselJ@1, xD ã 0, 8x, 4<D<,


8"Second root of J1 ", FindRoot@BesselJ@1, xD ã 0, 8x, 7<D<,
In[74]:=

8"Third root of J1 ", FindRoot@BesselJ@1, xD ã 0, 8x, 10<D<D êê TableForm

This means that the physically admissible values of the separation constant k are those given in the following
table (actually in its completion: I give only the leading fragment):
List@88k0,1 , 2.40483 ê a<, 8k0,2 , 5.52008 ê a<,
8k0,3 , 8.65373 ê a<<,
In[75]:=

88k1,1 , 3.83171 ê a<, 8k1,2 , 7.01559 ê a<,


8k1,3 , 10.1735 ê a<<D êê TableForm

and that the corresponding frequencies are given by


wi,j = c ki,j

The "fundamental" (lowest frequency) is the (0,1)-mode, and the next highest is seen to be not the (0,2)-mode
but the (1,1)-mode.
Let us, for graphical purposes, set a = c = 1 and define
In[76]:= fundamental@x_, y_, t_D :=

BesselJB0, 2.40483 x2 + y2 F Cos@0 ArcTan@y, xDD Cos@ 2.40483 tD


firstharmonic@x_, y_, t_D :=

BesselJB1, 3.83171 x2 + y2 F Cos@1 ArcTan@y, xDD Cos@ 3.83171 tD


higherharmonic@x_, y_, t_D :=

BesselJB5, 8.77148 x2 + y2 F Cos@5 ArcTan@y, xDD Cos@ 8.77148 tD

REMARK: Plot3D does not know about polar coordinates, works only in Cartesian coordinates…which is why we have described the
preceding modes as functions of x & y rather than r & theta.

Save.
10 Laboratory 5A.nb

kFF, 8x, -1, 1<,


1 2p
In[79]:= AnimateBPlot3DBEvaluateBfundamentalBx, y,
2.40483 10
8y, -1, 1<, PlotRange Ø 8-1, 1<, PlotPoints Ø 25F, 8k, 0, 9<F

REMARK: I do not know of any way to "trim the corner scrap," i.e., to omit the points where x 2 + y 2 > 1. Short of that, one might
usefully superimpose an image of the circular drum rim.

1 2p
In[80]:= AnimateBPlot3DBEvaluateBfirstharmonicBx, y, kFF,

8x, -1, 1<, 8y, -1, 1<, PlotRange Ø 8-1, 1<, PlotPoints Ø 25,
3.83171 10

Boxed Ø False,
Axes Ø FalseF, 8k, 0, 9<F

1 2p
In[81]:= AnimateBPlot3DBEvaluateBhigherharmonicBx, y, kFF,

8x, -1, 1<, 8y, -1, 1<, PlotRange Ø 8-1, 1<, PlotPoints Ø 35,
8.77148 10

Boxed Ø False,
Axes Ø False,
Mesh Ø FalseF, 8k, 0, 9<F

We notice that only in the first of those movies does the center of the drum move: in all other cases it is static.
In mathematical support of this observation we compute
Table@BesselJ@n, 0D, 8n, 0, 10<D êê N

Evidently Jn H0L = 0 unless n = 0. Physically: if you strike the drumhead at dead center you excite only the
In[82]:=

fundamental, and you excite higher and higher harmonics as you strike closer and closer to the rim…all of
which is entirely consistent with your direct experience.

‡ Modes of an Annular Drum


Such a drum possesses both an outer rim and an inner rim, which we take to be concentric circles of radii a and
b , with a<b . The vibrational physics is unchanged from the physics just discussed; what changes are the
boundary conditions. Bessel functions of the 2nd kind come now into play; separation leads us to
j1 @r_, q_, t_, k_, b_, m_D :=
HCos@bD BesselJ@m, k rD + Sin@bD BesselY@m, k rDL * Cos@m qD * Cos@c k tD

and to similar generalizations of the previously-defined functions j2 , j3 and j4 . The parameter b is a "mixing
angle." For each integral value of m we require of b and k that
Cos@bD BesselJ@m, k aD + Sin@bD BesselY@m, k aD

and
Cos@bD BesselJ@m, k bD + Sin@bD BesselY@m, k bD

both vanish. To show how one might discover the solutions of that pair of conditions I look to the case m = 0
and look to the case a = 0.2 , b = 1.0 . Define
Laboratory 5A.nb 11

both vanish. To show how one might discover the solutions of that pair of conditions I look to the case m = 0
and look to the case a = 0.2 , b = 1.0 . Define
In[83]:= rimfunction@b_, k_, r_D := Cos@bD BesselJ@0, k rD + Sin@bD BesselY@0, k rD

and use ContourPlot to identify all the points on the b , k -plane where
rimfunction@b, k, 0.2D = 0 :

In[84]:= innerrim = ContourPlot@rimfunction@b, k, .2D, 8b, -p, p<, 8k, .001, 10<,
PlotPoints Ø 100,
ContourShading Ø False,
Contours Ø 80<,
ContourStyle Ø 8Thickness@0.004D, RGBColor@0, 0, 1D<,
Frame Ø False,
Axes -> True,
Ticks Ø 88-p, -p ê 2, 0, p ê 2, p<, Automatic<,
AxesLabel Ø 8"mixing angle", "k"<D

Do the same for


rimfunction@b, k, 1.0D = 0 :

which will take a minute, be patient:

In[85]:= outerrim = ContourPlot@rimfunction@b, k, 1D, 8b, -p, p<, 8k, .001, 10<,
PlotPoints Ø 100,
ContourShading Ø False,
Contours Ø 80<,
ContourStyle Ø 8Thickness@0.004D, RGBColor@1, 0, 0D<,
Frame Ø False,
Axes -> True,
Ticks Ø 88-p, -p ê 2, 0, p ê 2, p<, Automatic<,
AxesLabel Ø 8"mixing angle", "k"<D

Intersection points in the following figure identify the points where both conditions are satisfied:

In[86]:= Show@innerrim, outerrimD

The k - coordinates of the intersection points (this figure, extended to higher k-values, together with similar
figures for m=1,2,3,…) give the natural frequencies of the annular drum. It would be interesting to pursue the
finer details…but the effort would take us too far away from our main topic.

‡ Summary Remarks Concerning the Separation Method


The following remarks are of general significance, but will be phrased as they relate to our experience with the
drum problem:
• Separation proceeded from a strong factorization assumption
u@r, q, tD = R@rD * A@qD * f@tD

and led to particular solutions of the PDE in question. But the general solution (it could be shown) can be
developed as a linear combination of those particular solutions.
• Spectral discreteness arose not from the PDE itself (which speaks in the language of smooth variation) but
from the associated boundary conditions. It is from this same circumstance that quantum mechanics acquires
the quantal discreteness to which its name refers.
12 Laboratory 5A.nb

• Spectral discreteness arose not from the PDE itself (which speaks in the language of smooth variation) but
from the associated boundary conditions. It is from this same circumstance that quantum mechanics acquires
the quantal discreteness to which its name refers.
• Mathematica made duck soup of the computational/graphic details, but we ourselves were responsible for the
controlling ideas~responsible, in particular, for the decision to work in polar coordinates.
• The decision to work in polar coordinates served us in two distinct ways: (1) it permitted separation of the
PDE, and (2) it permitted natural description of the boundary conditions. The theory in hand could be adapted
to a theory of wedge-shaped drumheads (more generally: any drumheads bounded by arcs of constant r and arcs
of constant q), but it has nothing to say about (say) elliptical drums, or annular drumheads with off-center holes.

REMARK: All strings have the same shape, and support therefore similar sets of harmonics. But drums (2-dimensional systems)
have different shapes, and therefore support distinct sets of harmonics. It becomes plausible to speculate that one can "hear the
shape of a drum."

• Our ability to adapt the separation of variables method to other physical problems is limited by our command
of separating coordinate systems, and we can expect in all events to be able to deal only with systems in which
the boundaries conform to the geometry of whatever coordinate system we have selected. (In other~more
general cases~we would have to fall back on numerical methods which are a vast subject in themselves.)
The latter circumstance has~more than any other~inspired development of a great number of wonder-
ful coordinate systems, about which Mathematica knows a great deal:

Save, close then reopen Mathematica, and proceed to Part B.


Physicist's Introduction to Mathematica
Laboratory 5
Part B

Curvilinear Coordinate Systems

Look up "curvilinear coordinates" in Help > Documentation Center… and you will be informed that Mathemat-
ica's knowledge of this subject resides in a Standard Package:
In[2]:= Needs@"VectorAnalysis`"D

When we open what Help has to say about that package we see a list and descriptions of fourteen 3-dimen-
sional coordinate systems (many of which you have never heard of), and are introduced to these commands:
In[3]:= ? CoordinateSystem

In[4]:= ? Coordinates

If we try those

In[5]:= 8CoordinateSystem, Coordinates@D<

we discover that Mathematica~until instructed otherwise~assumes us to be working in Cartesian coordinates,


and to be calling them x, y, z (or perhaps X, Y, Z). The names it presumes we will give to (say) spherical coordi-
nates are
In[6]:= Coordinates@SphericalD

and the command

In[7]:= ? CoordinatesToCartesian

tells us how Mathematica assumes the spherical coordinate system to have been constructed:

In[8]:= CoordinatesToCartesian@8r, q, f<, SphericalD

This means that Mathematica has defined

In[9]:= x@r_, q_, f_D := r Sin@qD Cos@fD


y@r_, q_, f_D := r Sin@qD Sin@fD
z@r_, q_, f_D := r Cos@qD

and so interprets q to be not latitude but "colatitude": q is 0 at the north pole, p at the south pole (not at the
equator, as is geographers and some physicists/mathematicians assume). This is, in particular, the spherical
system employed by Griffiths in his Introduction to Electrodynamics (see the endpapers). To clarify the situa-
tion, we have the command
2 Laboratory 5B.nb

and so interprets q to be not latitude but "colatitude": q is 0 at the north pole, p at the south pole (not at the
equator, as is geographers and some physicists/mathematicians assume). This is, in particular, the spherical
system employed by Griffiths in his Introduction to Electrodynamics (see the endpapers). To clarify the situa-
tion, we have the command
In[12]:= ? CoordinateRanges

In[13]:= CoordinateRanges@SphericalD

To discover how Mathematica would describe r, q, f in terms of x, y, z we command

In[14]:= CoordinatesFromCartesian@8x, y, z<, SphericalD

It is often useful to have before us a picture of the curvilinear coordinate system under consideration. To obtain
such images, we proceed
In[15]:= constantradius =

ParametricPlot3DB8x@1, q, fD, y@1, q, fD, z@1, q, fD<, :q, , p>, :f, 0,


p 3
p>F
8 2

In[16]:= constanttheta = ParametricPlot3DB

8x@r, p ê 4, fD, y@r, p ê 4, fD, z@r, p ê 4, fD<, :r, 0, >, :f, 0,


3 3
p>F
2 2

In[17]:= constantlongitude =

F, yBr, q, F, zBr, q, F>, :r, 0, >, :q,


p p p 3 p
ParametricPlot3DB:xBr, q, , p>F
8 8 8 2 8

In[18]:= Show@constantradius, constanttheta, constantlongitudeD

Notice that I have opened the figure up (restricted the range of the variables) to show better how the surfaces of
constant r, constant q and constant f interrelate.

Save.

The preceding figures contain no surprises, but their analogs in more exotic cases can be expected to teach us
useful things we did not know. Look, for example, to the following case:
In[19]:= Coordinates@ParaboloidalD

In[20]:= CoordinateRanges@ParaboloidalD

In[21]:= CoordinatesToCartesian@8v, u, f<, ParaboloidalD

In[22]:= CoordinatesFromCartesian@8x, y, z<, ParaboloidalD

In[23]:= Clear@x, y, z, u, v, fD

In[24]:= x@v_, u_, f_D := u v Cos@fD


y@v_, u_, f_D := u v Sin@fD

I-u2 + v2 M
1
z@v_, u_, f_D :=
2
Laboratory 5B.nb 3

In[27]:= constantv =

ParametricPlot3DB8x@1, u, fD, y@1, u, fD, z@1, u, fD<, 8u, 0, 3<, :f, 0,


3
p>F
2

After the following command you will get a message; hit OK and you'll be OK.

In[28]:= constantu =

ParametricPlot3DB8x@v, 1, fD, y@v, 1, fD, z@v, 1, fD<, 8v, 0, 3<, :f, 0,


3
p>F
2

In[29]:= constantphi =
F, yBv, u, F, zBv, u, F>, 8v, 0, 3<, 8u, 0, 3<F
p p p
ParametricPlot3DB:xBv, u,
8 8 8

In[30]:= Show@constantv, constantu, constantphiD

Drag the final figure to size, to improve clarity.

Save.

Many of the coordinate systems known to Mathematica are really parameterized families of similarly con-
structed coordinate systems, and acquire specific meaning only when numerical values have been assigned to
the parameters in question. Thus
In[31]:= ? ConfocalEllipsoidal

In[32]:= CoordinatesToCartesian@8l, m, n<, ConfocalEllipsoidal@l, m, n, a, b, cDD

In[33]:= ? Toroidal

In[34]:= CoordinatesToCartesian@8u, v, f<, Toroidal@u, v, f, aDD

After assigning some specific value to (a, b, c) in the former case, to a in the latter…we could use techniques
already described to construct informative graphical representations of such coordinate systems. The commands
In[35]:= ? Parameters

In[36]:= Parameters@ConfocalEllipsoidalD

In[37]:= ? ParameterRanges

In[38]:= ParameterRanges@ConfocalEllipsoidalD

are helpful in this general regard.


It is clear from the figures already in our possession that the coordinate surfaces intersect orthogonally. This
characteristic property of "named" coordinate systems is responsible for much of their interest and utility.
The theory of multivariable integration supplies
dxdydz = Jacobian * dudvdw

where the Jacobian is the determinant of the matrix of first partials. Look again, by way of illustration, to the
spherical coordinate system
4 Laboratory 5B.nb

where the Jacobian is the determinant of the matrix of first partials. Look again, by way of illustration, to the
spherical coordinate system
In[39]:= Clear@x, y, z, r, q, fD

In[40]:= x@r_, q_, f_D := r Sin@qD Cos@fD


y@r_, q_, f_D := r Sin@qD Sin@fD
z@r_, q_, f_D := r Cos@qD

If we were working by hand on paper, we would proceed along these lines:


D@x@r, q, fD, rD D@x@r, q, fD, qD D@x@r, q, fD, fD
In[43]:= matrixoffirstpartials = D@y@r, q, fD, rD D@y@r, q, fD, qD D@y@r, q, fD, fD
D@z@r, q, fD, rD D@z@r, q, fD, qD D@z@r, q, fD, fD

In[44]:= Det@%D êê Simplify

Mathematica has already released us from many minutes of tedious work. But Mathematica is smart enough to
do such work automatically:
In[45]:= ? JacobianMatrix

In[46]:= JacobianMatrix@Spherical@r, q, fDD

In[47]:= ? JacobianDeterminant

In[48]:= JacobianDeterminant@Spherical@r, q, fDD

Look at what Help has to say about the Calculus`VectorAnalysis` package and you will find that it provides
quite a number of similarly powerful/useful resources.
Mathematica has a built-in ability to compute the gradiant of a scalar field

In[49]:= Grad@f@x, y, zD, Cartesian@x, y, zDD

the divergence and curl of a vector field

In[50]:= Div@8u@x, y, zD, v@x, y, zD, w@x, y, zD<, Cartesian@x, y, zDD

In[51]:= Curl@8u@x, y, zD, v@x, y, zD, w@x, y, zD<, Cartesian@x, y, zDD

the Laplacian of a scalar field

In[52]:= Laplacian@f@x, y, zD, Cartesian@x, y, zDD

and the Laplacian of the Laplacian (which acquired physical importance in connection with the vibration of stiff
plates)
In[53]:= Biharmonic@f@x, y, zD, Cartesian@x, y, zDD

In the preceding demonstrations I have worked in Cartesian coordinates. And I have worked with non-specific
dummy functions to obtain generic results; insert specific functions, and Mathematica will return the associated
specific results.
The beauty of the situation is that Mathematica can do the same thing~with equal ease~in any of the coordi-
nate systems of which it has knowledge. Suppose we were working in spherical coordinates; then we would
have (for example)
Laboratory 5B.nb 5

The beauty of the situation is that Mathematica can do the same thing~with equal ease~in any of the coordi-
nate systems of which it has knowledge. Suppose we were working in spherical coordinates; then we would
have (for example)
In[54]:= Grad@f@r, q, fD, Spherical@r, q, fDD

~precisely as reported by Griffiths on the front endpaper of his Electrodynamics. For

In[55]:= Div@8u@r, q, fD, v@r, q, fD, w@r, q, fD<, Spherical@r, q, fDD

In[56]:= Simplify@%D

Mathematica has supplied here a result that does not much resemble the one reported by Griffiths, but the
difference is only notational, as I now demonstrate:

∂r Ir2 u@r, q, fDM + ∂q H v@r, q, fD Sin@qDL +


1 1
In[57]:= % ==
r2 r Sin@qD

∂f w@r, q, fD H* That's Griffiths' result on the right *L


1
r Sin@qD

In[58]:= Simplify@%D

The Laplacian occurs very commonly in the PDEs of mathematical physics, and is (in curvilinear coordinates)
tedious to compute longhand because it involves 2nd derivatives. Mathematica does the heavy labor in a jiffy:
In[59]:= Laplacian@f@r, q, fD, Spherical@r, q, fDD

∂r Ir2 ∂r f@r, q, fDM +


1
In[60]:= % ==
r2

∂q HSin@qD ∂q f@r, q, fDL + ∂f,f f@r, q, fD êê


1 1
2
r Sin@qD r2 Sin@qD2
Simplify H* That's again Griffiths on the right*L

Let us see how this result feeds into the separation strategy. First we assume
f@r, q, fD = R@rD * Y@q, fD

and compute

êê Simplify
Laplacian@R@rD Y@q, fD, Spherical@r, q, fDD
In[61]:=
R@rD Y@q, fD

Multiplication by r2 gives
r Y@q, fD H2 R£ @rD + r R££ @rDL R@rD Csc@qD2 YH0,2L @q, fD
In[62]:= + +
R@rD Y@q, fD R@rD Y@q, fD
R@rD Cot@qD YH1,0L @q, fD R@rD YH2,0L @q, fD
+
R@rD Y@q, fD R@rD Y@q, fD

in which r has been separated from the angular variables. Next we assume
Y@q, fD = P@qD * Q@fD

and find
6 Laboratory 5B.nb

Csc@qD2 ∂f,f HP@qD Q@fDL Cot@qD ∂q HP@qD Q@fDL ∂q,q HP@qD Q@fDL
In[63]:= + +
P@qD Q@fD P@qD Q@fD P@qD Q@fD

Division by Csc@qD2 gives


Cot@qD P£ @qD P££ @qD Csc@qD2 Q££ @fD
In[64]:= + +
Csc@qD2 P@qD Csc@qD2 P@qD Csc@qD2 Q@fD

in which q has been separated from f . These are the preparatory first steps in any number of physical discus-
sions in which spherical (or rotational) symmetry is present (as in the quantum theory of the hydrogen atom).

Save.

Total derivatives, total differentials, fractional change

I turn now to description of a powerful little tool of many uses:

In[65]:= ? Dt

Some illustrative applications:

In[66]:= DtAx2 y3 E

In[67]:= DtAx2 yn E

In[68]:= % ê. n Ø 3

An extra term appeared two commands ago because Mathematica assumes we intend to include n among the
variables; we can tell it that is not our intention
In[69]:= DtAx2 yn E ê. Dt@nD Ø 0

and in the case n=3 recover our former result:


In[70]:= % ê. n Ø 3

Here is the total time derivative of a dummy function of two variables

In[71]:= Dt@f@x, yD, tD

and here is the total second derivative


In[72]:= Dt@f@x, yD, t, tD

where
Laboratory 5B.nb 7

Dt@x, tD means x component of velocity

8t, 2<D means x component of acceleration


Dt@x, tD means y component of velocity

8t, 2<D means y component of acceleration


Dt@x,
Dt@y,

Kinetic Energy of a Particle in Spherical Coordinates

We begin by recalling how the spherical coordinates were introduced:

In[73]:= Clear@x, y, z, r, q, fD

In[74]:= x@r_, q_, f_D := r Sin@qD Cos@fD


y@r_, q_, f_D := r Sin@qD Sin@fD
z@r_, q_, f_D := r Cos@qD

We know that in Cartesian coordinates

IDt@x, tD2 + Dt@y, tD2 + Dt@z, tD2 M


m
In[77]:= kinetricenergy =
2

so in spherical coordinates have

IDt@x@r, q, fD, tD2 + Dt@y@r, q, fD, tD2 + Dt@z@r, q, fD, tD2 M êê Simplify
m
In[78]:=
2

If you have struggled as many times as I have to recreate this important result with pen and ink you will appreci-
ate the swift efficiency of the procedure just described.

Euclidean Metric in Parabolic Coordinates

We have interest in describing


squaredinterval = Dt@xD2 + Dt@yD2 + Dt@zD2

in parabolic coordinates. Recalling the definitions

In[79]:= Clear@x, y, z, u, v, fD

In[80]:= x@v_, u_, f_D := u v Cos@fD


y@v_, u_, f_D := u v Sin@fD

I-u2 + v2 M
1
z@v_, u_, f_D :=
2

we command

In[83]:= Dt@x@v, u, fDD2 + Dt@y@v, u, fDD2 + Dt@z@v, u, fDD2

In[84]:= Simplify@%D

This amounts to the statement that


8 Laboratory 5B.nb

u2 + v2
êê MatrixForm
0 0
In[85]:= metricmatrix = 0 2
u +v 2
0
0 0 u2 v2

In most applications (for example: to the quantum mechanics of the hydrogen atom) we would want to know
also that
In[86]:= Det@%D

In[87]:= Simplify@%D

Save.

Logarithmic Differentiation

The construction

In[88]:= Dt@Log@fDD

speaks very usefully (and dimensionlessly!) of how the a little change in f is related to the value of f . Look to
the familiar relationship

In[89]:= w= Lêg ;

taken from the elementary theory of pendula. We command

In[90]:= Dt@Log@wDD êê Simplify

and learn that a 1% increase in the value of g produces a 0.5% decrease in the value of w, while a a 1% increase
in the value of L produces a 0.5% increase in the value of w.
Elaborations of this basic idea permit one to describe with maximal simplicity and economy the fractional
change in this that results from a fractional change in that, and are encountered also in the theory of errors.

‡ Dimensional Analysis
Engineers tend to be more alert than physicists to the power of dimensional analysis. The subject is susceptible
to interesting formal development, but here I want only to discuss a computational problem poses by its rudi-
ments.
Suppose a physical system presents dimensioned variables/parameters q1 , q2 , q3 . We have interest in a variable
p, and expect the detailed theory of the system to result in a formula of the design
p = numeric * q1 x q2 y q3 z

The left and right sides of the anticipated equation must be dimensionally homogeneous, which means that if
@pD = Ma Lb Tc

@q1 D = Ma1 Lb1 Tc1

@q2 D = Ma2 Lb2 Tc2


Laboratory 5B.nb 9

@q3 D = Ma3 Lb3 Tc3

we must have
a ã a1 x + a2 y + a3 z
b ã b1 x + b2 y + b3 z
c ã c1 x + c2 y + c3 z

Dimensional analysis reduces, therefore, to a problem in linear algebra (made interesting because it is "linear
algebra in the exponent"). We will use Solve to tell us what the preceding equations say about the necessary
values of x, y, z .
Let us, for present purposes, agree to represent the physical dimensions of things by vectors, following
this convention:
mass = 81, 0, 0, 0<
length = 80, 1, 0, 0<
time = 80, 0, 1, 0<
temperature = 80, 0, 0, 1<

And let us adopt the language of a specific example: we pretend to be freshly interested in the theory of pen-
dula, and to anticipate a relationship of the form
frequency = HlengthLx HgravityLy Hmass of bobLz

We expect, in other words, to have


80, 0, -1, 0< = x 80, 1, 0, 0< + y 80, 1, -2, 0< + z 81, 0, 0, 0<

In[91]:= Solve@80, 0, -1, 0< ã x 80, 1, 0, 0< + y 80, 1, -2, 0< + z 81, 0, 0, 0<, 8x, y, z<D

The implication~already on dimensional grounds, independently of any appeal to the equations of pendular
motion~is that

w = Hdimensionless numericL * HgravityL ê HlengthL

Detailed dynamical argument supplies only the information that (in small angle approximation)
dimensionless numeric = 1

To prepare for a wider range of such arguments we might define


10 Laboratory 5B.nb

m = 81, 0, 0, 0< H* electron mass *L;


c = 80, 1, -1, 0< H* speed of light *L;
In[92]:=

— = 81, 2, -1, 0< H* Planck's constant *L;


G = 8-1, 3, -2, 0< H* gravitational constant *L;
chargesquared = 81, 3, -2, 0<; H* esu electronic charge2 *L;
k = 81, 2, -2, -1< H* Boltzmann's constant *L;
M = 81, 0, 0, 0< H* characteristic mass *L;
R = 80, 1, 0, 0< H* characteristic length *L;
t = 80, 0, 1, 0< H* characteristic time *L;
w = 80, 0, -1, 0< H* characteristic frequency *L;
v = 80, 1, -1, 0< H* characteristic velocity *L;
a = 80, 1, -2, 0< H* characteristic acceleration *L;
T = 80, 0, 0, 1< H* characteristic temperature *L;
energy = 81, 2, -2, 0< H* characteristic energy *L;
dimensionless = 80, 0, 0, 0<;

which we might use as follows:

‡ Application to Atomic/Molecular Physics

Expected Radius of Atom

In[107]:= Solve@R ã m x + HchargesquaredL y + — z, 8x, y, z<D

which gives
—2
BohrRadius =
m e2

Characteristic Atomic Energy

In[108]:= Solve@energy ã m x + HchargesquaredL y + — z, 8x, y, z<D

m e4
dissociationenergy =
—2

Characteristic Atomic Frequency

In[109]:= Solve@w ã m x + HchargesquaredL y + — z, 8x, y, z<D

m e4
BohrFrequency =
—3

Dissociation Temperature

In[110]:= Solve@T ã m x + HchargesquaredL y + — z + k u, 8x, y, z, u<D


Laboratory 5B.nb 11

m e4
dissociationtemperature =
—2 k

‡ Application to Planetary Physics

Surface Gravity

In[111]:= Solve@a ã M x + R y + G z, 8x, y, z<D

MG
g=
R2

Escape Velocity from Planetary Body

In[112]:= Solve@v ã M x + R y + G z, 8x, y, z<D

MG
escapevelocity =
R

‡ Application to Quantum Gravity

Planck Mass

In[113]:= Solve@M ã G x + c y + — z, 8x, y, z<D

c—
PlanckMass =
G

Planck Length

In[114]:= Solve@R ã G x + c y + — z, 8x, y, z<D

G—
PlanckLength =
c3

Planck Time

In[115]:= Solve@t ã G x + c y + — z, 8x, y, z<D

G—
PlanckTime =
c5
12 Laboratory 5B.nb

‡ Application to Quantum Electrodynamics

Fine Structure Constant

In[116]:= Solve@dimensionless ã — x + c y + chargesquared z, 8x, y, z<D


any power
e2
dimensionless =
—c

The fine structure constant arises fron setting any power = 1.

‡ Assignment of Numerical Value in Specified Units


This can be accomplished with the aid of the following resources:

In[117]:= Needs@"PhysicalConstants`"D
Needs@"Units`"D

Notice that we have here found it convenient to load two packages at the same time.

GravitationalConstant PlanckConstant
In[119]:= PlanckLength =
SpeedOfLight3

Unfortunately, the designer of these packages was addicted to SI units, and did not include resources powerful
enough to tell us that

Joule Newton Second4


= Meter
Kilogram2 Meter

To establish that fact we must import the information that


Joule = Newton Meter

Newton = Kilogram Meter Second-2

When we do so, we confirm that

IKilogram Meter Second-2 M Meter Second4


2

In[120]:=
Kilogram2 Meter

In[121]:= Simplify@%, Meter > 0D

The situation with regard to (for example) the fine structure constant a is even more of a tangle. For what
physicists call e2 the designer of the package calls
Laboratory 5B.nb 13

1
In[122]:= ElectronCharge2
4 p VacuumPermittivity

He does not appear to recognize the existence of "electrostatic units" (thinks of charge as dimensionally autony-
mous). And when he write PlanckConstant he means not — but 2p— . So we have
1 2p
In[123]:= a= ElectronCharge2
4 p VacuumPermittivity PlanckConstant SpeedOfLight

In[124]:= 1ê%

and have to import information to demonstrate that all the dimensions cancel:
Coulomb
Second
Meter Newton Second
In[125]:=
Coulomb2 Newton Meter
Coulomb

The SI system of units serves well the practical needs of experimentalists, but does mischief when foisted upon
theoretical authors (among them Griffiths) by misguided editors, for it is (I would argue) retrograde to create
supernumerary "fundamental units" (the SI system promotes "charge" to that status) when the thrust of great
discoveries (Newton's 2nd Law, Newton's G, Einstein's c, Planck's —, Millikan's e) has been to reduce their
number. Theorists generally prefer to assign "mechanical" dimension to charge. This, in view of the preceding
discussion, is most readily accomplished by writing
1 PlanckConstant
In[126]:= numericalESUelectronicchargesquared = SpeedOfLight
137.036 2p

or somewhat more neatly

In[127]:= ESUelectronicchargesquared = 2.30708*^-28 Kilogram Meter3 Second-2

One then has, for example, (borrowing from our dimensional determination of the Bohr radius)

I PlanckConstant M
2
2p
In[128]:= characteristicatomiclength =
ElectronMass ESUelectronicchargesquared

which in mass/length/time dimensions becomes

5.29177*^-11 J N Second4
Kilogram Meter 2
2
Second
In[129]:=
Kilogram2 Meter

In[130]:= CGS@%D

In the final step I have used the first of the following commands:

In[131]:= ? CGS

In[133]:= ? MKS

In[134]:= ? SI

Save.
14 Laboratory 5B.nb

Save.
Physicist's Introduction to Mathematica
Physics 200 Physics 50 Lab Revised for V6.0
Fall Semester 2000 Spring Semester 2006 Summer 2007
Nicholas Wheeler John Boccio John Boccio
REED COLLEGE Swarthmore College Swarthmore College
V4.0 Revised for V5.0

Laboratory 6
Part A

Recursive Processes

‡ Background
A major shift in the way physicists think can be traced to 1972, and for a curious reason. In that year Hewlett-
Packard introduced the HP-35, the first programmable calculator. It rapidly acquired the status of a cult object.
"HP-35 Clubs" appeared in scientific centers around the world. Physicists began to look forward to such dreary
events as faculty meetings as opportunities to twiddle with their HP-35s, started sharing tricks (slowly~those
were the days before e-mail), and interest was awakened in some mathematical phenomena that on first encoun-
ter seemed strange~the seeds of much that came after.
For example: Select a number x0 between 0 and 1, and repeatedly hit the Cos key. What you are thus computing
is
Cos@Cos@…@Cos@x0 DD …DD

It was observed that the output converged to 0.739085 independently of the value you had assigned to the
"seed" x0 . This result is really not unexpected in the light of the following calculation

In[2]:= FindRoot@Cos@xD ã x, 8x, .7<D

but is unforgettably impressive when done "in the hand". It can be phrased this way: iteration of
map : x Ø Cos@xD yields 0.739085 as a fixed point

People tried other maps, and found that some yielded an alternating pair of fixed points: a, b, a, b, a, b, …
Other maps yielded still more complicated patterns after many iterations. Some parameterized families of maps
parameterizedmap : x Ø fl @xD

were found to possess the property that slight l-adjustment produces radical alteration of the asymptotic pat-
tern. And sometimes the asymptotic output appears to be patternless/random, even though the map itself
contains no element of randomness…is "deterministic;" thus did the mathematical~also (as it develops) ubiqui-
tous physical~phenomenon of "deterministic chaos" come into focus.
2 Laboratory 6A.nb

were found to possess the property that slight l-adjustment produces radical alteration of the asymptotic pat-
tern. And sometimes the asymptotic output appears to be patternless/random, even though the map itself
contains no element of randomness…is "deterministic;" thus did the mathematical~also (as it develops) ubiqui-
tous physical~phenomenon of "deterministic chaos" come into focus.
Physicists soon learned to recognize instances/analogs of all of those phenomena in a wide range of physical
problems. My job here will be to illustrate how Mathematica can be used to approach such subject matter~a
subject matter that for the most part resists the techniques of classical analysis.

‡ Basic Tools
No longer is it necessary to "hit the Cos key many times." One can do so~proceed

In[3]:= Cos@0.2D

In[4]:= Cos@%D

In[5]:= Cos@%D

In[6]:= Cos@%D

etc., or better

In[7]:= Cos@Cos@Cos@Cos@0.2DDDD

~but Mathematica provides tools that do such things automatically:

In[8]:= ? Nest

In[9]:= ? NestList

In[10]:= ? FixedPoint

In[11]:= ? FixedPointList

In[12]:= HPtwiddle@x_D := Cos@xD

In[13]:= Nest@HPtwiddle, 0.2, 4D

In[14]:= Nest@HPtwiddle, 0.2, 100D

There already we have the previously-reported result of HP twiddling at a long faculty meeting! To watch the
convergence process we command
In[15]:= NestList@HPtwiddle, 0.2, 40D

Try a different seed:


In[16]:= NestList@HPtwiddle, 0.9, 40D

Abandon the details and proceed directly to the fixed point:

In[17]:= FixedPoint@HPtwiddle, 0.9D

The command
Laboratory 6A.nb 3

The command

In[18]:= FixedPointList@HPtwiddle, 0.9D

yields a longer-than-expected list because Mathematica is testing for constancy in much higher precision than
the printout.

REMARK: Mathematica always works in much higher precision than it routinely reports.

‡ Cobweb Plot
CobwebPlot@f_, 8x_, a_, b_<, x0_, n_IntegerD :=
CobwebPlot@f, 8x, a, b<, x0, 80, n<D
In[19]:=

In[20]:= CobwebPlot@f_, 8x_, a_, b_<, x0_, 8n0_, n_<D :=


Module@8data, fcn<,
fcn = Compile@x, fD;
data = NestList@fcn, s = Nest@fcn, x0, n0D, n - 1D;
y0 = If@n0 ã 0, 0, sD;
Show@Block@8$DisplayFunction = Identity<,
8Plot@f, 8x, a, b<D,
Graphics@88Thickness@0.0005D, Line@Drop@Prepend@

data ê. z_ ? NumericQ :> 88z, ff = fcn@zD<, 8ff, ff<<, 1D, 8s, y0<D,
Flatten@

-1DD<, 8PointSize@0.025D, Point@8s, y0<D<, 8GrayLevel@0.4D,


Line@88a, a<, 8b, b<<D<<D<D, PlotRange Ø 88a, b<, All<DD

Wagon's creation works like this:

In[21]:= CobwebPlot@HPtwiddle@xD, 8x, 0, p ê 2<, 0.2, 15D

Let us agree to give the name "diagonal" to the straight line that passes with unit slope through (0, 0) and (1, 1);
it is a graphical device for converting output f[x] into the input of f[f[x]]. The construction proceeds
curve Ø diagonal Ø curve Ø diagonal…

Such figures are ancient (I don't know how ancient, but were already old stuff when brought to my attention in a
Reed College math class nearly 50 years ago; they have been one of my favorate doodles ever since…but only
fairly recently did I learn that they had anything to do with physics!)…and provide a vivid representation of the
meanings both of f[f[…[f[x]]…]] and of the "iterative fixed point" concept. Such "cobwebs" are easy~and
fun!~to generate with pen and paper, but successive generations of doodlers failed to notice their most interest-
ing property. Those come into view only with computer assistance…and soon will. But first…
Look to our other example (same map, different seed):
In[22]:= CobwebPlot@HPtwiddle@xD, 8x, 0, p ê 2<, 0.9, 15D

Try a different map:

In[23]:= twiddlediddle@x_D := Sin@xD


4 Laboratory 6A.nb

In[24]:= CobwebPlot@twiddlediddle@xD, 8x, 0, p<, 1.0, 15D

In[25]:= CobwebPlot@twiddlediddle@xD, 8x, 0, p<, 2.0, 15D

Or this variant of that map:

In[26]:= CobwebPlot@2 twiddlediddle@xD, 8x, 0, p<, 2.0, 15D

In[27]:= CobwebPlot@3 twiddlediddle@xD, 8x, 0, p<, 2.0, 15D

No fixed point is now in evidence. CobwebPlot permits us to iterate (let us say) 275 times, but show only the
last 75; to get an improved sense of what's going on, let's do so
In[28]:= CobwebPlot@3 twiddlediddle@xD, 8x, 0, p<, 2.0, 8200, 75<D

‡ Logistic Map: Bifurcation and the Onset of Chaos


In Laboratory 4 we encountered the "logistic equation" (also called the Verhulst equation)
x '@tD ã x@tD H1 - x@tDL

that describes population growh with saturation (Verhulst process), which is characteristically "sigmoid":

In[29]:= DSolve@8x '@tD ã x@tD H1 - x@tDL, x@0D ã 0.1<, x@tD, tD

‰t
In[30]:= logisticpopulation@t_D :=
9.` + ‰t

exact =
Plot@logisticpopulation@tD, 8t, -5, 10<, PlotStyle Ø 8RGBColor@0, 0, 1D<D
In[31]:=

If we were motivated to solve the logistic equation numerically we would write


x@t + tD = x@tD + t x@tD H1 - x@tDL
x@0D = 0.1

and iterate. We are in position not to discuss very simply what would result from such a procedure:

x H1 - xL
1
In[32]:= Logistic@x_D := x +
10

In[33]:= values = NestList@Logistic, 0.1, 100D

, 8i, 0, 100<F
i
In[34]:= timepoints = TableB
10

Digression: How to make a binary list from two lists

The following remarks are, I think, self-explanatory: define

In[35]:= firstlist = 8a1 , a2 , a3 <


Laboratory 6A.nb 5

In[36]:= secondlist = 8b1 , b2 , b3 <

Recall that the suffix PkT serves to pluck the kth element out of a list: thus
In[37]:= firstlistP3T

(Recall also that P is produced Â[[Â .) Construct


In[38]:= binarylist = Table@8firstlistPkT, secondlistPkT<, 8k, 1, 3<D

which is a list of binary lists, with first element taken from firstlist, and second element taken from secÖ
ondlist. There is, however, a much better way (which, I am embarrassed to report, I learned only after this
text was drafted, while preparing the exercises): simply command
In[39]:= Transpose@8firstlist, secondlist<D

In[40]:= ? Transpose

The official description is not very clear, but the command clearly does job, and very efficiently. Here ends the
digression.

Using the technique just described (I use the first technique, but recommend that you in such contexts use
Transpose), we create the binary table

In[41]:= logisticdata = Table@8timepointsPkT, valuesPkT<, 8k, 1, 100<D

and use ListPlot to display that data:


In[42]:= approximate = ListPlot@logisticdataD

In[43]:= Show@exact, approximateD

Might we have taken bigger t-steps and, with less labor, still have obtained a satisfactory result? Back up and
retrace our steps:

x H1 - xL
1
In[44]:= Logistic2@x_D := x +
2

In[45]:= values2 = NestList@Logistic2, 0.1, 20D

timepoints2 = TableB , 8i, 0, 20<F


i
In[46]:=
2

In[47]:= logisticdata2 = Table@8timepoints2PkT, values2PkT<, 8k, 1, 20<D

In[48]:= approximate2 = ListPlot@logisticdata2D

In[49]:= Show@exact, approximate2D

Pretty good!…though little errors are now evident.

Save.

If we had serious interest in numerical solution of the logistic ODE we would be making t smaller and smaller.
But~our curiosity whetted~we abandon the ODE to concentrate on the logistic map itself, looking especially
to its asymptotic properties. We try a really big t (t = 1.8 )
6 Laboratory 6A.nb

If we had serious interest in numerical solution of the logistic ODE we would be making t smaller and smaller.
But~our curiosity whetted~we abandon the ODE to concentrate on the logistic map itself, looking especially
to its asymptotic properties. We try a really big t (t = 1.8 )
In[50]:= Logistic3@x_D := x + 1.8 x H1 - xL

In[51]:= values3 = NestList@Logistic3, 0.1, 50D

ListPlot@values3, PlotRange Ø 80, 1.5<,


AxesLabel Ø 8iterations, None<,
In[52]:=

PlotLabel Ø FontForm@"Logistic map with t = 1.800", 8"Helvetica", 16<D,


Ticks Ø 8Automatic, 81<<D

and find that the iterative process still approaches 1.00000 asymptotically (as a fixed point). But at t = 2.0

In[53]:= Logistic4@x_D := x + 2.0 x H1 - xL

In[54]:= values4 = NestList@Logistic4, 0.1, 50D

ListPlot@values4, PlotRange Ø 80, 1.5<,


AxesLabel Ø 8iterations, None<,
In[55]:=

PlotLabel Ø FontForm@"Logistic map with t = 2.000", 8"Helvetica", 16<D,


Ticks Ø 8Automatic, 81<<D

we are led asymptotically to an alternating pair of points. And at t = 2.542

In[56]:= Logistic5@x_D := x + 2.542 x H1 - xL

In[57]:= values5 = NestList@Logistic5, 0.1, 50D

ListPlot@values5, PlotRange Ø 80, 1.5<,


AxesLabel Ø 8iterations, None<,
In[58]:=

PlotLabel Ø 8"Logistic map with t = 2.542"<,


Ticks Ø 8Automatic, 81<<D

we are led asymptotically to a quartet of points that present themselves in a fixed cyclic order.
CobwebPlot can be used to clarify the situation: we define

In[59]:= logisticmap@t_D@x_D := x + t x H1 - xL

and proceed

In[60]:= CobwebPlot@logisticmap@1.8D@xD, 8x, 0, 1.5<, 0.1, 50D

which shows a single fixed point~to get a magnified view of the last 10 steps of the 50-step iteration we
command
In[61]:= CobwebPlot@logisticmap@1.8D@xD, 8x, 0.8, 1.2<, 0.1, 840, 10<D

~while at t = 2.0 we find

In[62]:= CobwebPlot@logisticmap@2.0D@xD, 8x, 0, 1.5<, 0.1, 50D


Laboratory 6A.nb 7

In[63]:= CobwebPlot@logisticmap@2.0D@xD, 8x, 0.8, 1.2<, 0.1, 840, 10<D

that we become trapped in endless circulation around a box, and at t = 2.542 we end up circulating around a
kind of "paperclip":
In[64]:= CobwebPlot@logisticmap@2.542D@xD, 8x, 0, 1.5<, 0.1, 50D

In[65]:= CobwebPlot@logisticmap@2.542D@xD, 8x, 0.4, 1.4<, 0.1, 840, 10<D

Save.

‡ Bifurcation Plot
It becomes natural at this point to try something like the following: (1) assign a value to t; (2) iterate long
enough (say 1000 steps) until things have stabilized, then record something like 100 consecutive values; (3)
increment the value of t and do the whole thing over again; (4) plot the data thus generated.

What follows is a good example of grown-up Mathematica programming. Just as Bach learned by copying out (and then writing
variations upon) Vivaldi scores, so would you learn some things by typing with your own hand the code. Try it sometime. You will, at
the very least, be reminded how difficult it is to type accurately; Mathematica is quite unforgiving~requires every bracket, every bit of
punctuation, every capital to be exactly right…and usually provides no clue as to where you have made your error. It is much easier
to type correctly than to edit in search of typos.

In[66]:= Needs@"Utilities`FilterOptions`"D;

In[67]:= elimDups@v_D := Module@8d = Sort@vD<,


Union@FoldList@If@Ò2 < 0.001 + Ò1, Ò1, Ò2D &, First@dD, Rest@dDDDD;

In[68]:= Options@BifurcationPlotD = 8PlotPoints Ø 100<;

BifurcationPlot@f_, 8r_, a_, b_<, 8x_, x0_<, 8iter0_, iterShow_<, opts___D :=


ModuleB8n<, n = PlotPoints ê. 8opts< ê. Options@BifurcationPlotD;
In[69]:=

makePts@8s_, v_<D := HPoint@8s, Ò1<D &L êü v;


cf = Compile@88r, _Real, 1<, 8x, _Real, 1<<, Evaluate@fDD;

rVals = HMin@Ò1, bD &L êü RangeBN@aD, b, NB FF;


b-a

data = Transpose@8rVals, elimDups êü Transpose@NestList@cf@rVals, Ò1D &,


n-1

Nest@cf@rVals, Ò1D &, Array@x0 &, nD, iter0D, iterShowDD<D;


Show@Graphics@8AbsolutePointSize@0.4`D, makePts êü data<D,
Sequence üü FilterRules@Flatten@8opts<D, Options@GraphicsDD,
Frame Ø True, PlotRange Ø 88a, b<, All<DF;

The program works like this:


In[71]:= logisticmap@r_D@x_D := x + r x H1 - xL

In[72]:= BifurcationPlot@logisticmap@rD@xD, 8r, 1.8, 3<, 8x, 0.1<, 8500, 10<,


PlotPoints Ø 1000D

Drag to nearly page-width to get a better view.


8 Laboratory 6A.nb

Drag to nearly page-width to get a better view.

Save.

We see that 1 is a fixed point until the control parameter r approaches 2, when the fixed point bifurcates (this is
called a "pitchfork bifurcation"). We then have a 2-cycle until r approaches about 2.45, when a second bifurca-
tion gives rise to a 4-cycle. We then pass rapidly through ascending powers of 2 until at about r = 2.58 we
enter a chaotic regime…which appears to be punctuated occasionally with "islands of cyclicity."
If we expand the view of the 2nd & 3rd orders of bifurcation (this is done simply by reducing the distance
between rmin and rmax ) we get the impression that they are just miniature copies of the initial bifurcation; i.e.,
that a principle of self-similarity is operative.
In[73]:= BifurcationPlot@logisticmap@rD@xD, 8r, 2.4, 2.6<, 8x, 0.1<, 8500, 10<,
PlotPoints Ø 1000,
GridLines Ø 882.448, 2.544, 2.565<, None<,
PlotRange Ø 80, 1.4<D

It was from an initial version of this figure that I determined where to place the gridlines that mark bifurcation points. Those were
improved with a couple generations of trial and error.

When we try to obtain a magnified view of the first pair of "islands of cyclicity"

In[74]:= BifurcationPlot@logisticmap@rD@xD, 8r, 2.6, 2.8<, 8x, 0.1<, 8500, 10<,


PlotPoints Ø 1000,
GridLines Ø 882.630, 2.742<, None<,
PlotRange Ø 80, 1.4<D

an intermediate island comes into view, which we look at more closely:

In[75]:= BifurcationPlot@logisticmap@rD@xD, 8r, 2.69, 2.71<, 8x, 0.1<, 8500, 10<,


PlotPoints Ø 1000,
GridLines Ø 882.7022<, None<,
PlotRange Ø 80, 1.4<D

We have discovered a 7-cycle, bracked on the left by a 6-cycle, and on the right by a 5-cycle. Look to the
associated cobweb plot:
In[76]:= CobwebPlot@logisticmap@2.7022D@xD, 8x, 0.2, 1.4<, 0.1, 8200, 30<D

Evidently the "Rule of 2n ," which holds prior to the onset of chaos, is suspended when we get to islands of
cyclicity.

Save.

Look finally to a magnified view of the big "3-cycle island" which lies in the neighborhood of r = 2.84:
Laboratory 6A.nb 9

In[77]:= BifurcationPlot@logisticmap@rD@xD, 8r, 2.8, 2.9<, 8x, 0.1<, 8500, 10<,


PlotPoints Ø 1000,
GridLines Ø 882.835<, None<,
PlotRange Ø 80, 1.4<D

Drag to size.

and to the associated cobweb:

In[78]:= CobwebPlot@logisticmap@2.835D@xD, 8x, 0.1, 1.4<, 0.1, 840, 10<D

In this case we see very clearly a miniaturized replication of the original family of pitchforks.
Working from such enlargements, I have located the low-order bifurcation points, and have in the next figure
used that improved data + higher resolution to place grid lines that show a bit better what is going on:
In[79]:= BifurcationPlot@logisticmap@rD@xD, 8r, 1.8, 3<, 8x, 0.1<, 8500, 10<,
PlotPoints Ø 1500,
FrameTicks Ø 881.996, 2.448, 2.543, 2.835<, Automatic, None, None<,
GridLines Ø 881.996, 2.448, 2.544, 2.565, 2.835<, None<D

Drag to size.

The following calculations

: >
2.448 2.544 2.565
In[80]:= , ,
1.996 2.448 2.544

In[81]:= Log@%D

In[82]:= 90.204126, 0.2041262 , 0.2041263 =

suggest that the placement of successive bifurcation points conforms to a simple pattern
Log@r2 D = Log@r1 D + k with k = 0.204126
Log@r3 D = Log@r2 D + k2 = Log@r1 D + k + k2

Log@r¶ D = Log@r1 D + k + k2 + k3 + ... = Log@r1 D +


k
1-k

On this basis we expect onset of chaos to occur at


0.204126

In[83]:= r¶ = 1.996 ‰ 1-0.204125

which looks to be about right. Down this road lies the universal Feigenbaum number 4.669…, which was
discovered by Michael Feigenbaum in 1975.

Save.
10 Laboratory 6A.nb

Comparison with a Couple of Other Maps: First Glimpse of "Universality"

Other maps gives rise to events which~remarkably~follow the same general pattern:

In[84]:= quadraticmap@r_D@x_D := r x H1 - xL

In[85]:= BifurcationPlot@quadraticmap@rD@xD, 8r, 2.8, 4<, 8x, 0.5<, 8500, 10<,


PlotPoints Ø 1000D

In[86]:= sinemap@r_D@x_D := r Sin@p xD

BifurcationPlot@sinemap@rD@xD, 8r, 0.6, 1<, 8x, 0.5<, 8500, 10<,


PlotRange Ø 80, 1<, PlotPoints Ø 1000D
In[87]:=

These figures have become icons of late 20th-Century mathematics. Another is the Mandelbrot Set, which
arises from iteration of the complex quadratic map
z Ø z2 + a

They speak simultaneously of


• bifurcation (successive generations of bifurcation);
• the abrupt onset of chaos (and its occasional~equally abrupt~disappearance);
• cryptic universality…
These notions live not only in the world of mathematical abstraction; symptoms of them have been found to be
all around us in the physical world, now that we have acquired eyes to see them. They can be found in physics
(in all of its flavors), biology, economics…and have become indispensable players in any modern conception of
"how the world works."

Coupled Nonlinear ODEs with Chaotic Solutions

We are in the habit of considering the world~those parts of it of greatest interest to physicists~to be described
not by iterated maps but by differential equations. It has only in fairly recent times come to be widely appreci-
ated (though it was evident to Poincare already a century ago) that fairly simple systems of coupled ODEs can
have wildly irregular solutions~solutions that depend very critically upon the prescribed initial conditions. I
give two examples:

Save.
Laboratory 6A.nb 11

‡ Rikitake's Model of Geomagnetic Field Reversal


In 1958, T. Rikitake (Proc. Camb. Phil. Soc. 54, 89|105) used a simple coupled disk dynamo system to model
the generation of the earth's magnetic field (see my Classical Electrodynamics 1980, page 139 or §6.1 in S. Neil
Rasband's Chaotic Dynamics of Nonlinear Systems 1990 for details; also the final pages of H. K. Moffatt,
Magnetic Field Generation in Electrically Conducting Fluids 1978). He was led to the following system of
coupled 1st order nonlinear ODEs:
x '@tD ã -m x@tD + u@tD y@tD
y '@tD ã -a x@tD - m y@tD + u@tD x@tD
u '@tD ã 1 - x@tD y@tD

m > 0 and a > 0 are parameters

It is easy enough for Mathematica to solve such coupled ODEs. Preliminar experimentation leads us to assign
illustrative values of 1.0 and 2.7 to m and a, and initial values of 1.0, 0 and 0.5 to x, y and u; we then obtain
In[88]:= numsoln = NDSolve@8
x '@tD ã -x@tD + u@tD y@tD,
y '@tD ã -2.7 x@tD - y@tD + u@tD x@tD,
u '@tD ã 1 - x@tD y@tD,
x@0D ã 1.0,
y@0D ã 0,
u@0D ã 0.5<, 8x, y, u<, 8t, 0, 200<, MaxSteps Ø 6000D

Mathematica reported itself unable to do what we had commanded with the 1000 default MaxSteps value. So we increased it.

How to display the numerical information which Mathematica has now at its disposal? Rikitaki himself plotted

In[89]:= Plot@Evaluate@x@tDD ê. %, 8t, 0, 200<, PlotRange Ø AllD

and
ParametricPlot@Evaluate@8x@tD, u@tD< ê. numsolnD,
8t, 0, 200<, PlotPoints Ø 2000D
In[90]:=

NOTE: Without the PlotPoints adjustment the figure would have been so kinky as to be almost unintelligible.

Those figures display, in their respective ways, the irregular sign-reversals that Rikitake (and later A. E. Cook
& P. H. Roberts, "The Rikitake two-disc dynamo system," Proc. Camb. Phil. Soc. 68, 644|649 (1965)) found to
be mathematically so surprising…and so suggestive of the physical facts of the matter (irregular reversals of the
geomagnetic field).
But in more recent literature one more frequently encounters figures of this design:
rikitakebutterfly = ParametricPlot3D@
Evaluate@8x@tD, y@tD, u@tD< ê. numsolnD, 8t, 0, 200<, PlotPoints Ø 2000,
In[91]:=

AxesLabel Ø 8"x", "y", "u"<D


12 Laboratory 6A.nb

Save.

This result provides a nice opportunity to exploit Mathematica's Live3D capability.


rikitakenoticks = ParametricPlot3D@
Evaluate@8x@tD, y@tD, u@tD< ê. numsolnD, 8t, 0, 200<, PlotPoints Ø 2000,
In[93]:=

Ticks Ø NoneD;

‡ Lorenz Model
Gentle heating of a thin layer of (say) peanut oil gives rise to orderly arrays of convection cells called Rayleigh-
Benard cells. In an effort to clarify aspects of this striking phenomenon (which interested him for meteorologi-
cal reasons) E. N. Lorenz, in 1963, subjected the equations of fluid dynamics to radical simplification (see §5.1
and Appendix A in Heinz Schuster's book, mentioned above; for Lorenz' original paper see "Deterministic
nonperiodic flow," J. Atmos. Sci 20, 130) and obtained equations
x '@tD ã -s x@tD + s y@tD
y '@tD ã r x@tD - y@tD - r x@tD z@tD
z '@tD ã x@tD y@tD - b z@tD

s > 0, r and b > 0 are parameters

which in their general features are somewhat reminiscent of Rikitaki's equations. Managing the Lorenz' equa-
tions as we managed Rikitake's, and setting our parameters/initial data to agree with page 893 of The Mathemat-
ica Book (where this example illustrates the use of NDSolve), we proceed
In[95]:= lorenz = NDSolve@8
x '@tD ã -3 x@tD + 3 y@tD,
y '@tD ã 26.5 x@tD - y@tD - u@tD x@tD,
u '@tD ã x@tD y@tD - u@tD,
x@0D ã 0,
y@0D ã 1,
u@0D ã 0<, 8x, y, u<, 8t, 0, 20<, MaxSteps Ø 3000D

In[96]:= Plot@Evaluate@x@tDD ê. %, 8t, 0, 20<, PlotRange Ø AllD

In[97]:= ParametricPlot@Evaluate@8x@tD, u@tD< ê. lorenzD, 8t, 0, 20<, PlotPoints Ø 2000D

ParametricPlot3D@Evaluate@8x@tD, y@tD, u@tD< ê. lorenzD,


8t, 0, 20<, PlotPoints Ø 2000,
In[98]:=

AxesLabel Ø 8"x", "y", "u"<D

The qualitative resemblance to results obtained from the (much less well studied) Rikitake model is striking.
We again detect the scent of some kind of "universality" principle…in which connection we note that both
systems are (not obviously, the way I have presented them) nonlinear forced dissipative systems.
I will not pursue this rich topic, because to do so would risk being seduced by the physics, and our present
assignment is simply to become acquainted with the utility of Mathematica. So I leave the Poincare maps,
Liapunov exponents, etc. for you to explore on your own, if someday you are so inclined.
You will appreciate that DEs are like iterated maps, in that they tell the state point where to go, where to go,
where to go… And that such rich structure as we have seen is exposed only by numerical analysis (which
Mathematica takes in easy stride). And the moral if it all: simple rules can have inexhaustibly complex
consequences.
Laboratory 6A.nb 13

You will appreciate that DEs are like iterated maps, in that they tell the state point where to go, where to go,
where to go… And that such rich structure as we have seen is exposed only by numerical analysis (which
Mathematica takes in easy stride). And the moral if it all: simple rules can have inexhaustibly complex
consequences.

Save.
Physicist's Introduction to Mathematica
Laboratory 6
Part B

Fitting Curves to Data

‡ Preliminary Remarks
It is increasingly rare for your activity in the laboratory to be describable as "hands-on" production of "raw
data." For it has become commonplace for a computer (else built-in special-purpose software) to stand between
you and the measurement device, interpreting your intentions to the device, and reporting back a pre-digested
account of what the device has detected. Which is OK if the software works, and if you know the true meaning
of its reports.
But occasionally you find yourself in the classical situation of
• trying to make statistical sense of tabulated experimental data;
• trying to find an effective way to display that data.
Concerning the first issue: Mathematica is general purpose mathematical software, not a "statistics engine." But
if you command
Needs@"Statistics`Master`"D

you gain access to about 185 standard statistical resources that permit you to do just about every statistical thing
that might occur to you. They are described in detail in Standard Add-on Packages. Those resources are easy
to use with the assistance of Help, and trying them out when you have occasion is a good (and fun) way to
acquire a useful degree of statistical power/sophistication.
We now describe how to import data into Mathematica. This is very easy…the essential command being

In[2]:= ? Import

I will not attempt to survey those topics here: you have, by now, learned a bit about how consult the vast Mathe-
matica literature (much of it at your electronic fingertips), and will best be instructed by urgent necessity.
I look instead to some techniques having to do with the graphical display of data (but will not concern myself
with the production of bar graphs, pie charts, etc.~stuff that Mathematica also knows how to do, but that
physicists seldom find useful).
2 Laboratory 6B.nb

‡ Curve-fitting Techniques
We begin by creating some artificial "data":

In[3]:= data = TableA9x, Sin@xD - Cos@xD + LogA1 + x2 E=, 8x, 0, 12, 1<E êê N

Try first this simple device, which we encountered already in Lab 1:

In[4]:= ? ListPlot

In[5]:= ListPlot@data, Joined Ø True, Epilog Ø 8PointSize@0.02`D, Point êü data<D

Here as always~when mystified by details in a sample command (here: the PlotJoined option, the use of
Epilog and the meaning of /@), we can ask Mathematica about them:

In[6]:= Options@ListPlotD

In[7]:= ? Epilog

In[8]:= ? êü

Just as easy to use but in most applications more interesting~and certainly more powerful (it contains the
preceding as a special case)~is the command
In[9]:= ? Interpolation

that asks Mathematica to use its smarts to come up with a "best" interpolation (which Mathematica does by
using piecewise cubic curves; we'll see in a moment what that means):
In[10]:= func = Interpolation@dataD

In[11]:= Plot@Evaluate@func@xDD, 8x, 0, 12<D

Looks to be a pretty good fit. How good? Superimpose the data points:
Plot@Evaluate@func@xDD, 8x, 0, 12<,
Epilog Ø 8PointSize@0.02D, Point êü data<D
In[12]:=

We should remember, however, that infinitely many alternative curves also thread precisely through the pre-
scribed set of points.
When asked to extrapolate from the given data, Mathematica~like everybody else~complains, hesitates, then
mutters some not-very-convincing things:
Plot@Evaluate@func@xDD, 8x, -2, 14<,
Epilog Ø 8PointSize@0.02D, Point êü data<D
In[13]:=

The interpolated function can, for most purposes, be treated like any other function; thus

In[14]:= func@10D


12
In[15]:= func@xD „ x
0

In[16]:= FindRoot@func@xD ã 4, 8x, 6<D

We are, in fact, already familiar with such objects: they are produced by (for example) NDSolve .
Laboratory 6B.nb 3

We are, in fact, already familiar with such objects: they are produced by (for example) NDSolve .
When we ask Mathematica about

In[17]:= Options@InterpolationD

we are informed that (as previously remarked) Interpolation uses cubics by default, the implication being
that we might elect to proceed otherwise. Try
In[18]:= func1 = Interpolation@data, InterpolationOrder Ø 1D

Plot@Evaluate@func1@xDD, 8x, 0, 12<,


Epilog Ø 8PointSize@0.02D, Point êü data<D
In[19]:=

and discover that we have simply reproduced the effect of PlotList with PlotJoinedØTrue . We have, in
particular, not managed to fit a straight line to the entire data set (the Interpolation procedure acts
"piecewise"). That, however, can be accomplished in the least squares sense

‚ Hdata - linear approximantL2 = minimum


data points

with the following very powerful command:

In[20]:= ? Fit

In[21]:= linearFit = Fit@data, 81, x<, xD

The highlighted detail asks Mathematica to do its best to fit the data to a curve of the form
a0 + a1 x

~which is just what Mathematica did. Look at the result:


Plot@linearFit, 8x, 0, 12<, Epilog Ø 8PointSize@0.02D, Point êü data<,
PlotRange Ø 8-2, 8<D
In[22]:=

Try a 4th order polynomial:

In[23]:= quadricFit = FitAdata, 91, x, x2 , x3 , x4 =, xE

Plot@quadricFit, 8x, 0, 12<, Epilog Ø 8PointSize@0.02D, Point êü data<,


PlotRange Ø 8-2, 8<D
In[24]:=

Try 8th order:

In[25]:= degreeEightFit = FitAdata, 91, x, x2 , x3 , x4 , x5 , x6 , x7 , x8 =, xE

Plot@degreeEightFit, 8x, 0, 12<, Epilog Ø 8PointSize@0.02D, Point êü data<,


PlotRange Ø 8-2, 8<D
In[26]:=

We know we would enjoy perfect success in 13th order (since there are 13 data points), but it's a little remark-
able that we did so well in 8th.
It's important, however, to realize that we are not married to polynomials: a mathematician with superhuman
insight might try
4 Laboratory 6B.nb

In[27]:= devilsFit = FitAdata, 9Sin@xD, Cos@xD, LogA1 + x2 E=, xE

and thus recover precisely the function we originally used to generate our toy data! A less insightful mathemati-
cian might have tried (say)
In[28]:= devilsapprenticeFit = FitAdata, 9Sin@xD, Cos@xD, 1, x2 =, xE

Plot@devilsapprenticeFit, 8x, 0, 12<,


Epilog Ø 8PointSize@0.02D, Point êü data<,
In[29]:=

PlotRange Ø 8-2, 8<D

which is nothing to write home about.

Digression: Surpression of an Artifact

Use a polynomial to generate some toy data


In[30]:= polynomialdata = TableA9x, 6 x + x2 =, 8x, 0, 12, 1<E êê N

and try to fit that data to (say) a quintic:

In[31]:= quinticFit = FitApolynomialdata, 91, x, x2 , x3 , x4 , x5 =, xE

The coefficients of x0 , x3 , x4 and x5 ~which should ideally be 0~are in fact tiny non-zero numbers (artifacts of
the numerical data-fitting process). Mathematica provides means to surpress such artifacts:
In[32]:= Chop@%D

In[33]:= ? Chop

Fourier Analytic Curve Fitting

Suppose our data were known/suspected on some grounds to be periodic:


periodicdata = 880., 2.5<, 81., 1.994315859499702<, 82., 2.9348821758069246<,
83., 3.4336975976543584<, 84., 2.7300544696118996<,
In[34]:=

85., 2.0155100778951174<, 86., 2.3713321277949326<,


87., 3.8151073498036303<, 88., 5.309245550327632<,
89., 5.7299679943906865<, 810., 4.910170935028343<,
811., 3.7996051401945024<, 812., 3.596306865687647<,
813., 2.5<, 814., 1.994315859499702<, 815., 2.9348821758069246<,
816., 3.4336975976543584<, 817., 2.7300544696118996<,
818., 2.0155100778951174<, 819., 2.3713321277949326<,
820., 3.8151073498036303<, 821., 5.309245550327632<,
822., 5.7299679943906865<, 823., 4.910170935028343<,
824., 3.7996051401945024<, 825., 3.596306865687647<<

Working by hand, I have duplicated our original data set, then modified the data at x=0 and x=1 to ellimiinate awkward "outliers."
Laboratory 6B.nb 5

In[35]:= Show@Graphics@8PointSize@0.02D, Point êü periodicdata<DD

It would then be natural to try

In[36]:= fourierFit = FitBperiodicdata, :


2p 2p
CosB0 xF, SinB0 xF,
13 13
2p 2p
CosB1 xF, SinB1 xF,
13 13
2p 2p
CosB2 xF, SinB2 xF,
13 13
2p 2p
CosB3 xF, SinB3 xF,
13 13
2p 2p
CosB4 xF, SinB4 xF>, xF
13 13

The following figure


Plot@fourierFit, 8x, 0, 24<,
Epilog Ø 8PointSize@0.02D, Point êü periodicdata<,
In[37]:=

PlotRange Ø 8-2, 8<D

shows the result (not remarkably, since we have used 10 functions to fit 13 data points) to be quite good.

Extrapolation

On the following evidence


Plot@fourierFit, 8x, 0, 37<,
Epilog Ø 8PointSize@0.02D, Point êü periodicdata<,
In[40]:=

PlotRange Ø 8-2, 8<D

we infer that Mathematica, though reluctant to extrapolate on the basis of Interpolate, is happy to do so on
the basis of information produced by Fit .

Now You're On Your Own: Good Luck!

I promised to "scratch the surface" of Mathematica. We have done that, but barely. Spend some time perusing
The Mathematica Book, the Standard Packages book and various commercial user guides (some are quite
specialized, bearing titles like "Mathematica in the Laboratory") to glimpse the vast wealth of material we have
altogether bypassed.
I will have succeeded if you carry away from these exercises a sense that Mathematica is a powerful tool,
relevant to the stuff that physicists do; that it is an approachable resource (and of how to approach it); that it is
fun; that it permits you to approach applied mathematics in an "experimental" frame of mind.
6 Laboratory 6B.nb

I will have succeeded if you carry away from these exercises a sense that Mathematica is a powerful tool,
relevant to the stuff that physicists do; that it is an approachable resource (and of how to approach it); that it is
fun; that it permits you to approach applied mathematics in an "experimental" frame of mind.

Save.

You might also like