Professional Documents
Culture Documents
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
‡ Notebooks
‡ Clear, Remove
Part A
‡ Simple Plotting
‡ Filled Plot
‡ Polar Plot
‡ List Plot
‡ Parametric Plot
Part B
Lab Contents.nb 3
Part B
‡ 3-Dimensional Plotting
‡ Combining Figures
Part A
‡ Implicit Plot
‡ Graphics Primitives
‡ Arrows
‡ Vector Fields
‡ Composite Figures…Revisited
Part B
‡ Animation
Physical Constants
Calendar
Maps
‡ Audio
Part A
‡ Basics
‡ Trigonometry
‡ Matrix Algebra
Part B
‡ Simple Definite/Indefinite Integrals
‡ Numerical Integration
‡ Multiple Integrals
Part A
‡
Lab Contents.nb 5
Harmonic Oscillator
Part B
Damped Harmonic Oscillator
Simple Pendulum
Part C
Damped Pendulum
Quantum Oscillator
Part D
Ballistics
Planetary Motion
Endpoint Conditions
Part A
‡ Techniques for Solving PDEs in Various Applied Settings
Waves on a String
Separation of Variables
Part B
‡ Curvilinear Coordinate Systems
Part A
‡ Background
‡ Basic Tools
Part B
‡ Fitting Curves to Data
Lab Contents.nb 7
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
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.
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[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.
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.
‡ 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 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
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.
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
„Ñ
Ñ
‡ 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.
a+x
1+ 1+
b
Notice that Mathematica has automatically supplied parentheses of the appropriate shape and size.
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)
‡ 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
In[15]:= Information@LerchPhiD
‚
¶
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
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]:= ?%
‚
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.
In[22]:= ? =
In[23]:= ? :=
In[24]:= ? ==
In[26]:= a=2
If we now write
In[28]:= a = Sin@xD
In[30]:= Simplify@%D
10 Laboratory 0.nb
In[31]:= Clear@aD
When we write
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[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
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.
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
In[49]:= ∂x I f@xD2 + xM
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
In[53]:= ∂u f@x, yD
which is a little bit surprising: Mathematica has uncomplainingly differentiated with respect to a parameter.
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]:=
An important instance of such a function is the Heaviside UnitStep function, which is a built-in resource of
Mathematica:
In[60]:= ? UnitStep
‡ 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]:=
<
>
<=
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
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
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
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
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
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[5]:= ? Frame
In[7]:= ? FrameTicks
In[8]:= ? Range
PlotStyle Ø 8AbsoluteThickness@2D<D
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:
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
Third Example:
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
which reveals a slight departure from linearity at the ends. The mystery is explained when we enter
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
‡ FilledPlot
Consider the following function
1
In[25]:= sechsquared@x_D := Sech@xD2
2
‡ sechsquared@xD „ x
¶
In[26]:=
-¶
‡ x sechsquared@xD „ x
¶
In[27]:=
-¶
‡ x sechsquared@xD „ x
¶
2
In[28]:=
-¶
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
‡ 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=
In[34]:= ? PolarPlot
, 8q, 0, 2 p<F
1
In[35]:= PolarPlotB
1 + .8 Cos@qD
, 8q, 0, 20 p<F
1
In[36]:= PolarPlotB
1 + .8 Cos@1.01 qD
‡ List Plot
In[39]:= ? ListPlot
In[40]:= ? Fibonacci
In[41]:= Fibonacci@50D
Note the techniques used to turn on the grid lines, and to adjust the point size.
‡ Parametric Plot
In[44]:= ? ParametricPlot
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
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]:=
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
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<,
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
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.
The following construction is familiar to anyone who has ever played with an oscilloscope:
In[55]:= Clear@a, b, x, yD
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.
‡ 3-Dimensional Plotting
In[2]:= ? Plot3D
In[3]:= Clear@fD
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
PlotPoints Ø 30,
AxesLabel Ø 8"x", "y", None<,
AxesEdge Ø 8Automatic, 81, -1<, 81, 1<<D
In[9]:= ? ViewPoint
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
Save.
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
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
Save.
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.
In[23]:= ? ParametricPlot3D
We start with a parameterized space curve, such as might arise from solution of equations of motion:
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
Torus
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):
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
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]:=
Similar devices might/will be used to represent the vibration of a drum head (triangular membrane).
Save.
Example~Revisited
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:
I have never encountered a situation in which the DensityPlot was the interesting way to go.
Save.
‡ 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,
In[52]:= ? GraphicsRow
Try it:
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]:=
Drag to size.
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
‡ Implicit Plot
To describe/draw a unit circle you might proceed
In[2]:= y@x_D := 1 - x2
but you only got half the intended figure, and it is missshapen; tweaking is required:
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
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
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:
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
In[29]:= ? PlotVectorField
In[30]:= Options@PlotVectorFieldD
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
‡
4 Laboratory 2A.nb
forcefield = HNeeds@"VectorFieldPlots`"D;
VectorFieldPlots`GradientFieldPlot@-wagonspotential@x, yD, 8x, -2, 2<,
In[36]:=
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
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?
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
8x, -4, 4<, 8y, -6, 6<, PlotPoints Ø 20, AspectRatio Ø AutomaticDL
VectorFieldPlots`GradientFieldPlot@-dipolepotential@x, yD,
An Example
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;
In[53]:= Options@ContourPlot3DD
PlotPoints Ø AutomaticD
and we can superimpose those upon the figure that represents the gradient of the scalar field:
Save
In[57]:= Show@PolyhedronData@"Octahedron"DD
parameters that control two radii and the mesh, as explained below.*L
In[65]:= ? Torus
In[67]:= ? MoebiusStrip
6 Laboratory 2A.nb
‡ 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:
Y@n_, x_D := 1 ì
1
- x2
In[70]:= n! 2p ‰ 4 He@n, xD
‡ 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]:=
-¶
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
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:
‡ Animation
The following animation shows how superimposed oscillator eigenstates contrive to mimic the sloshing charac-
teristic of classical oscillators. First we recall some definitions
Y@n_, x_D := 1 ì
1
- x2
In[3]:= n! 2p ‰ 4 He@n, xD
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:
: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
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]:=
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);
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
‡ 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.
See the Browser for further examples, discussion. We will return also to this topic in Laboratory 5.
‡ Calendar
In[31]:= Needs@"Calendar`"D
I learn that as of the date of writing she was 11,497 days old, and that
F
312 500 Day
In[36]:= NB
27
…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[41]:= World
Maps are susceptible to many optional variations, but the results are in all cases pretty schematic. See the
Browser for details.
Save.
‡ Audio
Mathematica ships with a built-in ability to turn waveforms f(t) into sound:
In[42]:= ? Play
The sonogram is often uninformative, but occasionally it does provide a useful "second handle" on your acous-
tic experience:
Beats
Twang
, 8t, 0, 3<F
t
-
In[45]:= PlayBSin@2 p 440 tD ‰ 0.5
Save.
, 8t, 0, 3<F
2 -
t
, 8t, 0, 3<F
3 -
t
‡
6 Laboratory 2B.nb
, 8t, 0, 3<F
4 -
t
, 8t, 0, 3<F
5 t
-
In[49]:= temperedthird = PlayBKSin@2 p 440 tD + SinB2 p 440 2 12 tFO ‰ 0.5
Later we will be in position to inquire in quantitative detail into the physical origin of those beats.
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.
In[52]:= Needs@"Audio`"D
In[53]:= ? Waveform
In[54]:= Options@WaveformD
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.
2 12 440 êê N
2
In[59]:=
2 12 440 êê N
4
In[61]:=
2 12 440 êê N
5
In[63]:=
In[66]:= ? AmplitudeModulation
In[67]:= ? RingModulation
In[69]:= ? FrequencyModulation
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
Mathematica provides means to undertake sophisticated analysis of images and signals. There are many
references.
8 Laboratory 2B.nb
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.
In[3]:= ? Expand
In[4]:= Options@ExpandD
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.
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]:=
êê 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
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.
In[28]:= ? FactorInteger
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:
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.
In[38]:= ? NSolve
In[39]:= SolveA2 + 3 x + 17 x2 ã 0, xE
In[40]:= NSolveA2 + 3 x + 17 x2 ã 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
In[45]:= SolveAx5 + x3 + 2 x2 + 3 x + 4 ã 0, xE
Now for a couple of useful definitions. The first permits one to plot lists of complex numbers
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]:=
We use this command to plot the roots of the quintic used in our recent numerical example:
Another example:
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[55]:= RootPlotA
1 + x + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + x12 + x13 + x14 + x15 + x16 , xE;
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.
and
6 Laboratory 3A.nb
and
x17 - 1
, 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:
The roots of
15
x4 - x2 + 1 ã 0
9
x2 + 1 ã 0, xFF êê TableForm
15
In[58]:= NBSolveBx4 -
9
15
In[59]:= RootPlotBx4 - x2 + 1, xF;
9
Nonlinear Pair
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
In[101]:= TrigExpand@%D
In[102]:= Simplify@%D
In[103]:= TrigReduceACos@aD3 E
In[105]:= TrigFactor@%D
In[106]:= TrigToExpASin@aD3 E
In[107]:= ExpToTrigA‰Â q 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
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:
Save
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
In[114]:= Needs@"Audio`"D
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
, 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:
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
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]:=
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
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
A=K O
a11 a12
In[137]:=
a21 a22
B=K O
b11 b12
b21 b22
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[144]:= columnvector.columnvector
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
Pretty clearly
R=K O
Cos@qD -Sin@qD
In[153]:=
Sin@qD Cos@qD
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
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
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
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[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
The "eigenvalues" of a matrix are the roots of its characteristic polynomial. To discover those we might proceed
In[170]:= ? Eigenvalues
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
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
Here and below I have used ; to surpress the screen-filling but not-very-informative output.
In[184]:= hermitian =
Hrandomcomplexmatrix + Transpose@Conjugate@randomcomplexmatrixDDL
1
2
The imaginary parts are pretty clearly computational artifacts, and are easily chopped off:
In[187]:= ? Chop
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
tracelesssymmetric = K O;
1 2
In[194]:=
2 -1
In[196]:= eigenvalue1 = - 5
1- 5
eigenvector1 = 2
1
eigenvalue2 = 5
1+ 5
eigenvector2 = 2
1
In[201]:= Simplify@%D
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.
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
‡
3 1
In[8]:= „x
-3 x2
‡ DiracDelta@y - 1D „ y
x
In[10]:=
-¶
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
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
‡ 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
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
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
‡ 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.
SinAx2 E + CosAy2 E
In[33]:= ∂x
1 - x2 - y2
SinAx2 E + CosAy2 E
In[34]:= ∂y
1 - x2 - y2
SinAx2 E + CosAy2 E
In[35]:= ∂x,y
1 - x2 - y2
SinAx2 E + CosAy2 E
In[36]:= ∂y,x
1 - x2 - y2
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
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
In[47]:= g '@xD
g ''@xD
g '''@xD
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
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[58]:= Simplify@%D
Notice the notation that Mathematica has here adopted to represent derivatives of order greater than 2.
‡ D@f@uD, uD „ u
x
In[67]:=
0
Mathematica is comfortable also with dummy functions of several variables. For example, we have
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[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[78]:= Simplify@%D
In[79]:= x2 + y2 - 10 x y == a2
so we have finally
24 a2
Hy - 5 xL3
In[80]:= y ''@xD ==
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[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.
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.
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
we see that the function is perfectly well-behaved there, and are not surprised to obtain
In[93]:= Limit@f@xD, x Ø 0D
In[95]:= Limit@f@xD, x Ø ¶D
Second Example
In[96]:= Clear@gD
1
In[97]:= g@x_D :=
x
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
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
, 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
, 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!
‚ n-z
¶
In[121]:=
n=1
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
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
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.
The general solution is obvious, but let us ask Mathematica to do the work:
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.
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[11]:= 1 + x2 ê. x Ø tom
So in place of
Wagon writes
8D@psol, tD ã a qsol,
D@qsol, tD ã b psol< êê Simplify
In[18]:=
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
and look to the particular solution that arises from setting C[1] = 1
In[22]:= % ê. C@1D Ø 1
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.
From
we see that the population grows if P < 5, becomes steady at P = 5, diminishes if P > 5. Proceeding
we obtain the particular population curve in which we have a declared interest. We plot it:
Laboratory 4A.nb 5
p H5 - pL
>,
1
VectorFieldPlots`VectorFieldPlotB: ,
1 + Hp H5 - pLL 2
1 + Hp H5 - pLL 2
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
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 +
In[32]:= typicalposition = 3 ê 4;
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
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
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
Mathematica thinks for awhile, then informs us that it is unable to supply an analytical solution
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]:=
g1 = ParametricPlot@
Evaluate@8dampedpendulum3000, D@dampedpendulum3000, tD<D, 8t, 0, 10<,
In[6]:=
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
g2 = ParametricPlot@
Evaluate@8dampedpendulum4000, D@dampedpendulum4000, tD<D, 8t, 0, 10<,
In[9]:=
g3 = ParametricPlot@
Evaluate@8dampedpendulum5000, D@dampedpendulum5000, tD<D, 8t, 0, 10<,
In[12]:=
g4 = ParametricPlot@
Evaluate@8dampedpendulum6000, D@dampedpendulum6000, tD<D, 8t, 0, 10<,
In[15]:=
g5 = ParametricPlot@
Evaluate@8dampedpendulum7000, D@dampedpendulum7000, tD<D, 8t, 0, 10<,
In[18]:=
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]:=
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]:=
g8 = ParametricPlot@
Evaluate@8dampedpendulum9000, D@dampedpendulum9000, tD<D, 8t, 0, 10<,
In[30]:=
g9 = ParametricPlot@
Evaluate@8dampedpendulum10000, D@dampedpendulum10000, tD<D, 8t, 0, 10<,
In[33]:=
Save.
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]:=
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]:=
G2 = ParametricPlot@
Evaluate@8dampedpendulum8122, D@dampedpendulum8122, tD<D, 8t, 0, 10<,
In[42]:=
There are yet other ways to represent the results produced by DSolve[ ] and NDSolve[
]commands.
Save.
Laboratory 4C.nb 7
Save.
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
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
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
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
Simple adjustment of the initial data permits us to trawl for odd solutions:
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
-
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
Defining
x J 1x N
x2
-
f1 @x_D :=
‰ 2
In[64]:=
2
‡ f1 @xD „ x
¶
2
In[66]:=
-¶
Enlarging upon this experience, we omit the initial data specifications (seems to be Mathematica's preference)
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
and that
Laboratory 4C.nb 11
‡ f3 @xD „ x
¶
2
In[79]:=
-¶
‡ f5 @xD „ x
¶
2
-¶
‡ f7 @xD „ x
¶
2
-¶
‡ f9 @xD „ x
¶
2
-¶
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
‡ Y3 @xD „ x
¶
2
In[88]:=
-¶
‡ Y5 @xD „ x
¶
2
-¶
‡ Y7 @xD „ x
¶
2
-¶
‡ 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
Ticks Ø None,
AspectRatio Ø AutomaticF, 8k, 0, 19<F;
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>,
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>,
Ticks Ø None,
AspectRatio Ø AutomaticF, 8k, 0, 29<F;
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 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,
Ticks Ø None,
AspectRatio Ø Automatic,
PlotStyle Ø RGBColor@0, 0, 1DF, 8k, 0, 19<F;
In[15]:= Show@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@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@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
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
In[28]:= subperturbedorbit =
x@tD y@tD
The precession is prograde in the former case, retrograde in the latter. The following experiment
In[30]:= barelysuperperturbedorbit =
x@tD y@tD
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[33]:= x@t_, T_, a_, b_, w_D := a Cos@t wD + H-a Cot@T wD + b Csc@T wDL Sin@t wD
, .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
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
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
In[5]:= DSolve@∂t u@x, tD ã a ∂x,x u@x, tD, u@x, tD, 8x, t<D
‡ 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
In[11]:= Simplify@%D
In[12]:= Clear@u, f, gD
The command
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:
And Mathematica, once pointed in the right direction, is quick to agree with d'Alembert:
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[22]:= j@x, tD
but if we planned to speak about it in a modern lecture hall we would probably find it more effective to make a
movie:
Second Example
F+ F
x 1 x
In[25]:= u@x, tD := SinBt - CosB3 t +
c 3 c
In[27]:= Simplify@%D
In[29]:= j@x, tD
+ 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.
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[35]:= f@xD
g@xD
In[38]:= Simplify@%D
which does indeed reproduce our known (and previously plotted) starting point. Look to this more interesting
case:
K‰ O
1 -Hx+tL2 í 4 -Hx-tL2 í 4
In[41]:= u@x, tD := +‰
2
In[43]:= Simplify@%D
Laboratory 5A.nb 5
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.
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
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
and write
u@x, yD = F@r@x, yD, q@x, yDD
with
In[52]:= ? ArcTan
In[54]:= Simplify@%D
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:
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
A ''@qD + m2 A@qD = 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
In[64]:= ? BesselJ
In[65]:= ? BesselY
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]:=
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]:=
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]:=
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 :=
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
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.
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
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:
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.
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:
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[7]:= ? CoordinatesToCartesian
tells us how Mathematica assumes the spherical coordinate system to have been constructed:
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
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 =
In[17]:= constantlongitude =
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[23]:= Clear@x, y, z, u, v, fD
I-u2 + v2 M
1
z@v_, u_, f_D :=
2
Laboratory 5B.nb 3
In[27]:= constantv =
After the following command you will get a message; hit OK and you'll be OK.
In[28]:= constantu =
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
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[33]:= ? Toroidal
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
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
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[47]:= ? JacobianDeterminant
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
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
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:
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
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
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.
In[65]:= ? Dt
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
where
Laboratory 5B.nb 7
In[73]:= Clear@x, y, z, r, q, fD
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.
In[79]:= Clear@x, y, z, u, v, fD
I-u2 + v2 M
1
z@v_, u_, f_D :=
2
we command
In[84]:= Simplify@%D
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 ;
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
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
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
Detailed dynamical argument supplies only the information that (in small angle approximation)
dimensionless numeric = 1
which gives
—2
BohrRadius =
m e2
m e4
dissociationenergy =
—2
m e4
BohrFrequency =
—3
Dissociation Temperature
m e4
dissociationtemperature =
—2 k
Surface Gravity
MG
g=
R2
MG
escapevelocity =
R
Planck Mass
c—
PlanckMass =
G
Planck Length
G—
PlanckLength =
c3
Planck Time
G—
PlanckTime =
c5
12 Laboratory 5B.nb
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
In[120]:=
Kilogram2 Meter
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
One then has, for example, (borrowing from our dimensional determination of the Bohr radius)
I PlanckConstant M
2
2p
In[128]:= characteristicatomiclength =
ElectronMass ESUelectronicchargesquared
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
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
In[8]:= ? Nest
In[9]:= ? NestList
In[10]:= ? FixedPoint
In[11]:= ? FixedPointList
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
The command
Laboratory 6A.nb 3
The command
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]:=
data ê. z_ ? NumericQ :> 88z, ff = fcn@zD<, 8ff, ff<<, 1D, 8s, y0<D,
Flatten@
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
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
that describes population growh with saturation (Verhulst process), which is characteristically "sigmoid":
‰t
In[30]:= logisticpopulation@t_D :=
9.` + ‰t
exact =
Plot@logisticpopulation@tD, 8t, -5, 10<, PlotStyle Ø 8RGBColor@0, 0, 1D<D
In[31]:=
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
, 8i, 0, 100<F
i
In[34]:= timepoints = TableB
10
Recall that the suffix PkT serves to pluck the kth element out of a list: thus
In[37]:= firstlistP3T
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
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
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
and find that the iterative process still approaches 1.00000 asymptotically (as a fixed point). But at t = 2.0
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
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
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
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;
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"
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
Drag to size.
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.
: >
2.448 2.544 2.565
In[80]:= , ,
1.996 2.448 2.544
In[81]:= Log@%D
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
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
Other maps gives rise to events which~remarkably~follow the same general pattern:
In[84]:= quadraticmap@r_D@x_D := r x H1 - xL
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
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
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
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]:=
Save.
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
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
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
‡ 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
In[4]:= ? ListPlot
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
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
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
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
In[20]:= ? Fit
The highlighted detail asks Mathematica to do its best to fit the data to a curve of the form
a0 + a1 x
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
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
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
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
shows the result (not remarkably, since we have used 10 functions to fit 13 data points) to be quite good.
Extrapolation
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 .
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.