143
Physicist's Introduction to Mathematica Physics 200 Physics 50 Lab Revised for V6.0 Fall Semester 2000 Spring Semester 2006 Summer 2007 Nicholas Wheeler John Boccio John Boccio REED COLLEGE Swarthmore College Swarthmore College V4.0 Revised for V5.0 TABLE OF CONTENTS Within any given Mathematica notebook you can use the resources in the Find menu to locate keywords, whether they occur in text or commands. Fifteen notebooks live within the MM V6 Lessons folder; the follow- ing list of section titles is intended to guide you to the particular notebook most likely to contain the material of immediate interest.

Ma Thematic A Manual

Embed Size (px)

Citation preview

Page 1: Ma Thematic A Manual

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

TABLE OF CONTENTS

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

Page 2: Ma Thematic A Manual

Lab 0

‡ Why Bother to Learn Mathematica?

‡ Getting Started…and Stopped

‡ Terminating a Running Calculation

‡ Notebooks

‡ Input Techniques & Tips

‡ Sources of Information & Help

‡ Three Primary Flavors of =

‡ Clear, Remove

Lab 1: Basic Graphics

Part A

‡ Simple Plotting

‡ Filled Plot

‡ Polar Plot

‡ List Plot

‡ Parametric Plot

‡ Some Remarks about Memory Management

Part B

2 Lab Contents.nb

Page 3: Ma Thematic A Manual

Part B

‡ 3-Dimensional Plotting

‡ Combining Figures

Lab 2: Basic Graphics (Part 2)

Part A

‡ Implicit Plot

‡ Graphics Primitives

‡ Arrows

‡ Vector Fields

‡ Other Graphics Available as Standard Add-ons

‡ Composite Figures…Revisited

Part B

‡ Animation

‡ Exporting Mathematica Graphics to TeX

‡ Installing Standard Add-on Packages

‡ Some Miscellaneous Resources

Physical Constants

Conversion from One System of Units to Another

Calendar

Maps

‡ Audio

‡ Finding Things in Notebooks

Lab Contents.nb 3

Page 4: Ma Thematic A Manual

Finding Things in Notebooks

Lab 3: Algebra, Trigonometry, Calculus

Part A

‡ Basics

‡ Finding the Roots of a Polynomial

‡ Graphical Representation of Complex-valued Functions

‡ Solving Systems of Simultaneous Equations

Application to Collision Theory

‡ Trigonometry

‡ Matrix Algebra

Part B

‡ Simple Definite/Indefinite Integrals

‡ Numerical Integration

‡ Functions Defined by Integrals

‡ Multiple Integrals

‡ Ordinary & Partial Differentiation

‡ Limits & Series

Lab 4: Ordinary Differential Equations

Part A

4 Lab Contents.nb

Page 5: Ma Thematic A Manual

‡ Solving ODEs in Various Applied Settings

Exponential Population Growth

Logistic Model of Limited Population Growth

Harmonic Oscillator

Part B

Damped Harmonic Oscillator

Harmonically Forced Damped Harmonic Oscillator

Simple Pendulum

Part C

Damped Pendulum

Quantum Oscillator

Part D

Ballistics

Planetary Motion

Endpoint Conditions

Lab 5: Partial Differential Equations & Related Topics

Part A

‡ Techniques for Solving PDEs in Various Applied Settings

Waves on a String

Separation of Variables

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

Lab Contents.nb 5

Page 6: Ma Thematic A Manual

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

Modes of an Annular Drum

Summary Remarks Concerning the Separation Method

Part B

‡ Curvilinear Coordinate Systems

‡ Total Derivatives, Differentials, Fractional Change

Application to Dimensional Analysis

Physical Units and Conversions…Revisited

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

Part A

‡ Background

‡ Basic Tools

‡ Wagon's Cobweb Plot

Logistic Map and the Onset of Chaos

Digression: How to Make a Binary List from Two Lists

‡ Wagon's Bifurcation Plot

‡ Coupled Nonlinear ODEs with Chaotic Solutions

Part B

‡ Fitting Curves to Data

6 Lab Contents.nb

Page 7: Ma Thematic A Manual

Fitting Curves to Data

Preliminary Remarks

Curve-fitting Techniques

Lab Contents.nb 7

Page 8: Ma Thematic A Manual

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

Laboratory 0

Why Bother to Learn Mathematica?

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

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

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

Getting Started…and Stopped

Page 9: Ma Thematic A Manual

Getting Started…and Stopped

I begin with a cautionary word: It is inevitable that you will from time to time (and especially in the beginning) steer Mathematica off the road. Do not panic .... that is the way to learn how it works.

Mathematica comes in two large and semi-autonomous packages:

• the computing engine itself, called the "kernel" ;

• the "front end", which mediates the flow of information between you and the kernel (or perhaps several kernels, running simultaneously on several computers). The front end manages screen display, graphics, access to the Help Browser and much else, and can perform certain tasks independently of the kernel; it was conceived and designed not by Wolfram himself, but by Theodore Gray.

I will proceed in the assumption that you are running Mathematica 6.0 on Mac OSX. Occasional small details change if you are running Windows; I am unfamiliar with them, and will not attempt to describe them.

You already have the front end running (starting Mathematica does that). To turn on the kernel and (more to the point) to establish communication between the front end and the kernel the traditional procedure is to type 2+2 and hit ENTER:

In[2]:= 2 + 2

During the interval the kernal was starting your input acquired an input number, and the output (when at last it appeared) was assigned a corresponding output number.

To experience the often blinding speed of Mathematica, try

In[3]:= 1000!

In[4]:= Expand@H1 + xL^100DThat was fast. How fast?

In[5]:= % êê Timing

The {0.xxxxxx,…} informs us that the calculation kept the kernel busy for 0.xxxxxx seconds. Clearly % recalled the last result. %% recalls the one before that and so on.

The long response to 1000! is cluttering up the notebook. So we Select then double click the "cell" contain-ing that In/Out pair; the output disappears, and the cell marker acquires an arrow at its base. Select/double click again and the output reappears. Do the same for the expansion of (1+x)^100.

During the interval when a command keeps the kernel occupied for several seconds, the title bar will indicate what is happening. Try the command below and it should indicate Running… for awhile, then Rendering…-Running…

In[7]:= Plot3D@Sin@2 p xD Cos@2 p yD, 8x, -1, 1<, 8y, -1, 1<, PlotPoints Ø 200D êê Timing

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

2 Laboratory 0.nb

Page 10: Ma Thematic A Manual

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

‡ Terminating a running calculationNot infrequently you will want, for one reason or another, to terminate a calculation. Maybe you've realized you have asked Mathematica to do the wrong thing, or the calculation has run so long that you suspect (Mathemat-ica returns no progress reports) something may be wrong with your command, or Mathematica reports back that it has been caught up in an endless loop. In such cases the first thing to try is

Ì-. Simple abort: hold down Ì and press period…and wait.

Equivalently, you might select Abort Evaluation from the front end's Kernel menu.The kernel has to "back up," so the wait is roughly proportional to how deep you were into the calculation, but eventually (after perhaps several minutes) an Out[#]=Aborted should appear.

But Mathematica, once started, reveals a single-minded reluctance to quit, and after a long wait you may con-clude that the simple technique just described is not going to work. Or perhaps you are simply tired of waiting. Try

Ì-q Simple quit Mathematica: you will be asked if you want to Save your work,

then both the front end and the kernel will shut down, and you should Restart. If that is ineffective, try hitting

ÌıÂ Hard dump of the kernel. Save your work, Quit Mathematica, Restart.

Finally, you can force quit Mathematica…but will lose any unsaved open documents. It is in anticipation of such an event (or other misfortune) that you should be careful to

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

Notebooks

Mathematica documents are called "notebooks," and wear the suffix .nb Open the File menu, select New (alternatively: hit Ì-N), and you have created a new notebook. Use File > Save As… (alternatively: ˜Ì-S) to name and save the notebook.

Notebooks can be rendered in various "styles"~designs intended for different uses. Mathematica is shipped with 20 canned designs: open Format > Style Sheet to see the list. Try them, one after the other, to see what they do to this text.

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

Laboratory 0.nb 3

Page 11: Ma Thematic A Manual

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

Different canned styles come equipped with different sets of options~few in some cases, numerous in others. Open Format and activate Show ToolBar. Go to Notepad Style and open the ToolBar menu: it shows only four options. Now go to Textbook Style: it shows 29 options. It was (primarily for the reason just stated, but also) to obtain a workable set of options that I elected to work in TutorialBook Style.

Under Format you find Edit Style Sheet… and someday you may have occasion to do just that. The Mathemat-ica Book tells you how. But for the moment we have already in hand all the resources we will need. My gen-eral advice:

• Mathematica is intolerant of typos~all capitalization, every brace and bracket, every bit of punctuation must be exactly right~so work with magnification big enough that you can clearly distinguish . from , etc.

• Show the ToolBar; it is a great aid to the insertion of section titles, explanatory text, etc.

• Make the page large, yet small enough to leave room on the screen an input palette or two.

• When opening a closed notebook to resume work, start with something simple like the standard 2+2; otherwise the front end may be unable to find and connect with the kernel.

Input techniques & tips

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

TIP : The correct way to type (stuff) is not ( then stuff then ) but

H L then the stepleft key ¨ then stuff

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

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

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

4 Laboratory 0.nb

Page 12: Ma Thematic A Manual

• 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).

‡ PalettesVersions 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-x3 dx one had to enter

In[8]:= Integrate@x Exp@-x^3D, 8x, 0, Infinity<DThat, 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-x3 dx one would enter

In[10]:= ‡0

x ‰-x3 „x

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

In the Palettes menu you see several options:

Open Calculus. Close.

Open LinearAlgebra. Close.

Open MultiVariableCalculus. Close.

Open Plotting. Close.

Open AlgebraicManipulation. Close.

Open BasicMathInput. Close.

Open BasicTypesetting. Close.

Open SpecialCharacters. Close.

Open SlideShow. Close.

Open NotebookLauncher. Redundant with Format > Style Sheet. Close

Laboratory 0.nb 5

Page 13: Ma Thematic A Manual

Open Calculus. Close.

Open LinearAlgebra. Close.

Open MultiVariableCalculus. Close.

Open Plotting. Close.

Open AlgebraicManipulation. Close.

Open BasicMathInput. Close.

Open BasicTypesetting. Close.

Open SpecialCharacters. Close.

Open SlideShow. Close.

Open NotebookLauncher. Redundant with Format > Style Sheet. Close

I have highlighted the palettes I find most useful. There is a large element of redundancy present in the design of the standard palettes; for example, everything on the BasicMathInput palette can be found also on one or another of the more specialized palettes.

Many palette buttons produce characters with one or more blank boxes. ⁄Ñ=ÑÑ † is a good example. Use Í to

advance from box to box, entering data as you go.

What distinguishes the É boxes from the Ñ boxes? Suppose, having written

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

6 ‰-a x

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

‡Ñ

Ñ

6 ‰-a x „Ñ

and can use the enter key to construct/execute

In[11]:= ‡0

6 ‰-a x „x

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

Look to another example: Select

1 + 1 +a + x

b

and hit ‡Ñ to create

1 + 1 +a + x

b

2

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

Do the same with Sin[x] and you discover that, while Mathematica does not recognize the common construc-tion sin2[x], neither does it require anything so cumbersome as Hsin@xDL2.

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."

6 Laboratory 0.nb

Page 14: Ma Thematic A Manual

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

Palette buttons are a great aid to speed and legibility. But they require use of the mouse, and in some situations their repetitive use can become tedious (though deft use of Cut/Copy/Paste often permits accelerated escape from the tedium). It is useful to know that the action of palette buttons can often be achieved directly from the keyboard. Open File > Palettes > CompleteCharacters, then open (say) Technical Symbols and Shapes and Icons. Move the selection arrow around over the face of the palettes and watch the bottom of the window. You will discover, for example, that

› can be produced by typing the TEX-like command \[Watch Icon]. (Here I had to introduce an artificial space; delete it to see why!)

Ÿ can be produced by typing either Âmath or \[Mathematica Icon]. (Artificial space)

⁄ can be produced by typing \[Kernel Icon]. (Artificial space)

œ can be produced either by Â:-@ or by \[Freaked Smiley]. (Artificial space)

É can be produced either by Âspl or by \[Selection Placeholder]. (Artificial space)

Ñ can be produced either by Âpl or by \[Place holder]. (Artificial space)

‰ can be produced either by Âee or by \[Exponential E]. (Artificial space)

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

p can be produced either by Âp or by \[P i]. (Artificial space)

Etc. There is a limit to how many such commands one can remember, but the point is one does not need to remember them: palette design automatically reminds one of their existence.

In addition to the lengthy list of "longform" commands \[Etc] and a shorter list of "shortform" commands Âetc it is possible (on Macintosh) to enter some symbols with commands of the form ı-p (which pro-duces p); use ı- and ı˜- to run through the keyboard and discover the possibilities~most of which are uninteresting.

Sources of Information & Help

‡ Built-in SourcesOpen 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

Laboratory 0.nb 7

Page 15: Ma Thematic A Manual

In[12]:= ‚j=0

¶ xj

Hj + uLn

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

In[13]:= ? LerchPhi

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

In[15]:= Information@LerchPhiDLerchPhi@z, s, aD gives the Lerch transcendent PhiHz, s, aL, etc.

But~backing up to our starting point~if in

In[16]:= ‚j=0

¶ xj

Hj + uLn

we Select the output and then open Help > Find Selected Function… we are instantly presented with a detailed description of the "Lerch transcendent" and of its relation to (among others) the Riemann zeta and polylog functions.

Distinct from and complementary to Information is Options. We can ask Mathematica itself to describe the difference:

In[17]:= ? Information

In[18]:= ? Options

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

In[19]:= Plot@Sin@xD, 8x, 0, p<Dand then become curious about the options which were available to us; to discover those, we enter

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

In[21]:= ? %

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

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

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

8 Laboratory 0.nb

Page 16: Ma Thematic A Manual

Mathematica power = ‚t=today

then

Problems successfully solved

And don't be too proud to save also~perhaps in a separate notebook of "Stolen Tricks"~a record of the ideas developed by others that seem to you interesting, or potentially useful. Quite a number of those will be encoun-tered as we proceed.

Sometimes your "tricks" will consist of programs that run a dozen or more lines (Mathematica programs are seldom very long; that heavy work was done by the designers of the software), but more often they will consist of felicitous selections from among available options. The value of your Tricks Notebooks will be much increased if you include explanatory text and references~easy if you open Format > Show ToolBar. Notice also that you need not add to the end of your notebook: you can introduce new material interstitially, in confor-mity with some organizational pattern, with categories labled with appropriate Section titles.

Use the resources of the Find menu to locate material in your notebooks. The task is made easier if you embel-lish your notebooks with appropriate tag words and phrases.

Three Primary Flavors of =

Enter the following:

In[22]:= ? =

In[23]:= ? :=

In[24]:= ? ==

What, in plain words, do those statements mean?

In[25]:= ? =

Mathematica understands that when we write

In[26]:= a = 2

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

In[27]:= a + 1

If we now write

In[28]:= a = Sin@xDwe have reassigned meaning to a:

In[29]:= 1 - a2

In[30]:= Simplify@%D

Laboratory 0.nb 9

Page 17: Ma Thematic A Manual

In[31]:= Clear@aDWhen we write

In[32]:= g = Plot@x Sin@xD, 8x, 0, 100<Dwe 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@gDA mnemonically better name in this instance might have been something like

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

In[35]:= Show@firstgraphDIt was to permit such practice that the designers of Mathematica interpret xy to be a compound symbol or "name," and require use of some special device to signify "multiplication":

x y Here the ¯ signifies multiplication; alternatively, use

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

x.y if x and y are matrices.

Conversely, spaces cannot be used in names.

It is permitted to make several assignments simultaneously. Try

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

In[36]:= p = Tomq = Dickr = Harry

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

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

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

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

‡ Delayed Assignment: Functional Definition

In[41]:= ? :=

Were we to write

In[42]:= f = x17

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

10 Laboratory 0.nb

Page 18: Ma Thematic A Manual

(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

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

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[48]:= List@f@1D, f@2D, f@3DDH*Look up List in the Master Index. Be sure to open "Further Examples"*L

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

In[50]:= Plot@f@xD, 8x, 0, 1<, PlotRange Ø AllDNote 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, yDwhich is not at all surprising, and

In[53]:= ∂u f@x, yDwhich is a little bit surprising: Mathematica has uncomplainingly differentiated with respect to a parameter.

Piece-wise functional definition:

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

In[54]:= Clear@veeD

Laboratory 0.nb 11

Page 19: Ma Thematic A Manual

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

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

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

vee@x_D := 1 ê; 1 < x

H* ê; means "use this rule when…"*L

In[59]:= Plot@vee@xD, 8x, -2, 2<DAn important instance of such a function is the Heaviside UnitStep function, which is a built-in resource of Mathematica:

In[60]:= ? UnitStep

In[61]:= Plot@UnitStep@xD, 8x, -2, 2<,PlotStyle Ø 88RGBColor@1, .3, 0D, [email protected]<<, PlotRange Ø 80, 2<D

‡ 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

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

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

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

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

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

‡ Secondary Flavors of = , and of some of its RelativesConstructions like

===

=!= H*negation of the preceding*L<

>

<=

12 Laboratory 0.nb

Page 20: Ma Thematic A Manual

>=

return True/False output, and are used mainly in Mathematica programming. The first asks whether the expression on the left is structurally identical to the expression on the right

In[70]:= 3 x2 === ∂x x3

In[71]:= Sin@xD2 + Cos@xD2 === 1 H*identity, but not "structural identity"*L The final pair ask § ? and ¥ ? respectively, but require the expressions on left and right to be numeric, not symbolic : with the Schwarz inequality in mind, we ask

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

but when we ask the general instance of the same question

In[73]:= Ia12 + a22 + a32M Ib12 + b22 + b3

2M >= Ha1 b1 + a2 b2 + a3 b3L2

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

In[74]:= distance@t_D := r +1

2 g t2

Check to see what you have created

In[75]:= distance@tDand 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@gDYou 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"?

Laboratory 0.nb 13

Page 21: Ma Thematic A Manual

In[79]:= ? Clear

Enter the command

In[80]:= Clear@r, gD H*Erases previous assignment*Land check to confirm that the command did its work:

In[81]:= r

In[82]:= g

‡ Clearing functionsMathematica'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 assignEyour first command in every computation.

14 Laboratory 0.nb

Page 22: Ma Thematic A Manual

your first command in every computation.

We will have no immediate need of the more comprehensive command

In[90]:= ? ClearAll

Save.

Laboratory 0.nb 15

Page 23: Ma Thematic A Manual

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

Laboratory 1Part 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.

‡ ResourcesYour 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.

Page 24: Ma Thematic A Manual

‡ Simple Plotting

In[2]:= ? Plot

First Example:

In[3]:= Plot@Tan@xD, 8x, 0, 20<DNotice that Mathematica has no trouble at all with the infinities.

Notice also that the output consists not of the figure, but of the not-too-informative expression -Graphics-. That output can be surpressed by appending a ; to our original command (try it). We will henceforth adopt that practice.

We look now to a few basic elaborations of the preceding basic command:

In[4]:= Plot@Tan@xD, 8x, 0, 20<, Frame Ø TrueD

In[5]:= ? Frame

In[6]:= Plot@Tan@xD, 8x, 0, 20<, Frame Ø True,FrameTicks Ø 8Range@0, 6 p, pD, Automatic, None, None<D

In[7]:= ? FrameTicks

In[8]:= ? Range

In[9]:= Plot@Tan@xD, 8x, 0, 13 p ê 2<, Frame Ø True,FrameTicks Ø 8Range@0, 6 p, pD, Automatic, None, None<,PlotStyle Ø 8AbsoluteThickness@2D<D

In[10]:= Plot@Tan@xD, 8x, 0, 13 p ê 2<, Frame Ø True,FrameTicks Ø 8Range@0, 6 p, pD, Automatic, None, None<,PlotStyle Ø [email protected], 0, 0.8D, [email protected]<D

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

In[12]:= ? Thickness

In[13]:= ?? AbsoluteThickness

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

Second Example:

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

Mathematica tries to show "the interesting part" of a figure, with the result that it has here clipped off some detail. I give two ways to override that defect:

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

2 Laboratory 1A.nb

Page 25: Ma Thematic A Manual

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

Third Example:

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

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

The graph is remarkable for its unexpected linearity. To gain a sense of how linear it truly is, we might proceed as follows:

In[18]:= Clear@aD

In[19]:= a = [email protected] + [email protected]

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

.5 x H*Equation of straight line passing through a

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

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

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

In[22]:= Series@Sin@xD + ArcSin@xD, 8x, 0, 15<Dand discover that the Maclaurin expansion has no terms of orders 2, 3, or 4. We made first use here of the following resource:

In[23]:= ? Series

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

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

‡ FilledPlotConsider the following function

In[25]:= sechsquared@x_D :=1

2 Sech@xD2

has all the properties required of a probability distribution

In[26]:= ‡-¶

sechsquared@xD „x

In[27]:= ‡-¶

x sechsquared@xD „x

In[28]:= ‡-¶

x2 sechsquared@xD „x

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

Laboratory 1A.nb 3

Page 26: Ma Thematic A Manual

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

In[29]:= Plot@sechsquared@xD, 8x, -4, 4<DDirect visual comparison with the Gaussian with the same variance is enhanced if one makes use of a resource provided as a Standard Add-On:

In[30]:= gaussian@x_, s_D :=1

s 2 p ExpB-

1

2 x

s

2

F

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

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

‡ Polar PlotNot 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

r =constant

1 + eccentricity µ cos HqLThe relevant software is provided as an add-on to Mathematica:

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

In[34]:= ? PolarPlot

In[35]:= PolarPlotB 1

1 + .8 Cos@qD, 8q, 0, 2 p<F

Slight adjustment causes the orbit to precess:

In[36]:= PolarPlotB 1

1 + .8 [email protected] qD, 8q, 0, 20 p<F

Try these further examples of polar plots:

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

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

‡ List Plot

In[39]:= ? ListPlot

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

In[40]:= ? Fibonacci

In[41]:= Fibonacci@50DMake a table of the first 10 Fibonacci numbers

4 Laboratory 1A.nb

Page 27: Ma Thematic A Manual

In[42]:= fib = Table@Fibonacci@nD, 8n, 10<Dand use ListPlot to display that data graphically:

In[43]:= ListPlot@fib, GridLines Ø Automatic, Prolog Ø AbsolutePointSize@5DDNote the techniques used to turn on the grid lines, and to adjust the point size.

‡ Parametric Plot

In[44]:= ? ParametricPlot

First Example: Simple Cycloid

A circle of unit radius rolls along the x-axis. We are interest in the curve traced by a point P marked on the circumference of the circle. Working from a sketch, we are led to define

In[45]:= x@q_D := q - Sin@qDy@q_D := 1 - Cos@qD

In[47]:= ParametricPlot@8x@qD, y@qD<, 8q, 0, 6 p<DThe 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:

In[48]:= ParametricPlot@8x@qD, y@qD<, 8q, 0, 4 p<, AspectRatio Ø Automatic,Frame Ø True, FrameTicks Ø 880, 2 p, 4 p<, 80, 1, 2<, None, None<,PlotStyle Ø 8RGBColor@0, 0, 1D, [email protected]< D

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

"Hypocycloids" and "hypercycloids" result when the point P is placed interior/exterior to the unit circle. Here we make the appropriate modifications:

In[49]:= Clear@rD

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

In[52]:= ParametricPlot@88x@q, 0.5D, y@q, 0.5D<,8x@q, 1.0D, y@q, 1.0D<, 8x@q, 1.5D, y@q, 1.5D<<, 8q, 0, 4 p<,AspectRatio Ø Automatic, Frame Ø True,FrameTicks Ø 880, 2 p, 4 p<, 80, 1, 2<, None, None<,PlotStyle Ø 8RGBColor@1, 0, 0D, 8<, RGBColor@0, 0, 1D<D

Second Example: Epicycles

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

Laboratory 1A.nb 5

Page 28: Ma Thematic A Manual

In[53]:= ParametricPlotBEvaluateB

8Cos@qD, Sin@qD< +1

2 8Cos@7 qD, Sin@7 qD< +

1

3 :CosB-17 q +

p

2F, SinB-17 q +

p

2F>F,

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

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

Note the use here of

In[54]:= ? Evaluate

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

Third Example: Lissajous Figures

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

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

In[56]:= x@t_, a_, a_D := a Cos@a tDy@t_, b_, b_, d_D := b Cos@b t + dD

In[58]:= ParametricPlot@8x@t, 2, 2D, y@t, 1, 3.00, p ê 2D<,8t, 0, 16 p<, AspectRatio Ø AutomaticD

In[59]:= ParametricPlot@8x@t, 2, 2D, y@t, 1, 3.01, p ê 2D<,8t, 0, 16 p<, AspectRatio Ø AutomaticD

Fourth Example: Cornu Spiral

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

In[60]:= cornu@t_D := :‡0

t

SinAu2E „u, ‡0

t

CosAu2E „u>

In[61]:= ParametricPlot@Evaluate@cornu@tDD, 8t, -10, 10<,AspectRatio Ø AutomaticD êê Timing

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

6 Laboratory 1A.nb

Page 29: Ma Thematic A Manual

Physicist's Introduction to MathematicaLaboratory 1Part B

‡ 3-Dimensional Plotting

In[2]:= ? Plot3D

The basic command is very simple:

In[3]:= Clear@fD

In[4]:= f@x_, y_D := Ix2 + 3 y2M ‰1-x2-y2

In[5]:= Plot3D@f@x, yD, 8x, -2, 2<, 8y, -3, 3<DHere we exercise a few of the available options:

In[6]:= Plot3D@f@x, yD, 8x, -2, 2<, 8y, -3, 3<,BoxRatios Ø 84, 5, 3<,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

In[8]:= doublehump = Plot3D@f@x, yD, 8x, -2, 2<, 8y, -3, 3<,BoxRatios Ø 84, 5, 3<,PlotPoints Ø 30,AxesLabel Ø 8"x", "y", None<,AxesEdge Ø 8Automatic, 81, -1<, 81, 1<<D

It is easy to adjust the viewpoint

In[9]:= ? ViewPoint

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

In[11]:= Show@doublehump, Boxed Ø False, Axes Ø None, ColorFunction Ø HWhite &LDOne 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:

Page 30: Ma Thematic A Manual

In[13]:= ? RevolutionPlot3D

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

In[15]:= RevolutionPlot3DAr2, 8r, 0, 3<, 8q, 0, 2 p<, Boxed Ø False,

Axes Ø False, PlotPoints Ø 40, BoxRatios Ø 81, 1, 2<E

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

In[17]:= SphericalPlot3DBq, 8f, 0, p<, :q, 0,7 p

2>,

Boxed Ø False,Axes Ø False,

PlotPoints Ø 60F êê Timing

Save.

A Physical Example: Larmor Radiation

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

In[18]:= larmor = SphericalPlot3DASin@fD2, 8f, 0, p<, 8q, 0, p<,Boxed Ø False,Axes Ø False,PlotPoints Ø 40E

Then we construct a line indicating the direction in which the charged particle has been assumed to be accelerating

In[19]:= acceleration = Graphics3D@8AbsoluteThickness@2D,RGBColor@1, 0, 0D, Line@880, 0, 0<, 80, 0, 2<<D<, Boxed Ø False D

In[20]:= Show@accelerationDAnd finally we superimpose the two figures:

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

Save.

I have never had physical need of the following resource

In[22]:= ? ListPlot3D

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

2 Laboratory 1B.nb

Page 31: Ma Thematic A Manual

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

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

In[23]:= ? ParametricPlot3D

Parameterized Space Curve

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

In[24]:= ParametricPlot3DB: t

10 Sin@10 tD, t

10 Cos@10 tD, t ‰

-t

10>, 8t, 0, 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@fDy@f_, q_D := Sin@qD Sin@fDz@f_, q_D := Cos@qD

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

:f, 0,3 p

2>, :q,

p

20,19 p

20>,

Boxed Ø False, Axes Ø NoneF

Torus

Here is a variant of the same basic idea:

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

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

:u, -1

6 p,

3

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

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):

Laboratory 1B.nb 3

Page 32: Ma Thematic A Manual

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

Example: Eigenstates of a Quantum Particle in a Triangular Box

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

In[32]:= Clear@m, n, x, yD

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

In[34]:= groundstate =

ContourPlot@boxfunction@x, y, 1, 2D, 8x, -1, 1<, 8y, -1, 1<, PlotPoints Ø 100D

In[35]:= excitedstate =

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

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

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:

In[37]:= ContourPlot@boxfunction@x, y, 11, 15D, 8x, -1, 1<,8y, -1, 1<, PlotPoints Ø 100, ContourShading Ø FalseD

Drag to size to get a better view.

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

Save.

Example~Revisited

We previously used Plot3D to display the function

In[38]:= f@x, yDNow we use ContourPlot to display the same information:

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

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

4 Laboratory 1B.nb

Page 33: Ma Thematic A Manual

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

In[40]:= ContourPlot@boxfunction@x, y, 2, 3D, 8x, -1, 1<, 8y, -1, 1<,PlotPoints Ø 100,ColorFunction Ø HHue@1 - Ò ê 2D &LD

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

In[41]:= ? DensityPlot

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

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

Save.

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

In[43]:= ContourPlot@f@x, yD, 8x, -2, 2<, 8y, -3, 3<,PlotPoints Ø 100,FrameTicks Ø 8Range@-2, 2D, Range@-3, 3D, None, None<,ContourShading Ø False,Contours Ø 81, 0.5<,ContourStyle Ø [email protected]<, [email protected]<<D

‡ Combining FiguresSuppose~having produced a set of figures

In[44]:= ? BesselJ

In[45]:= g0 = Plot@BesselJ@0, xD, 8x, 0, 20<Dg1 = Plot@BesselJ@1, xD, 8x, 0, 20<Dg2 = Plot@BesselJ@2, xD, 8x, 0, 20<Dg3 = Plot@BesselJ@3, xD, 8x, 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, g3DNote 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

Laboratory 1B.nb 5

Page 34: Ma Thematic A Manual

In[51]:= Plot@8BesselJ@0, xD,BesselJ@1, xD,BesselJ@2, xD,BesselJ@3, xD<, 8x, 0, 20<D

to recreate the same effect.

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

In[52]:= ? GraphicsRow

Try it:

In[53]:= GraphicsRow@8g0, g1, g2<DTo 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:

In[59]:= b0 = Plot@BesselJ@0, xD, 8x, 0, 20<,PlotRange Ø 8-0.5, 1<, Ticks Ø 8Automatic, 81<<D

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

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

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

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

Drag to size.

Here is a different arrangement:

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

Drag to size.

Save.

6 Laboratory 1B.nb

Page 35: Ma Thematic A Manual

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

Laboratory 2Part A

Basic Graphics (Part 2)

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

‡ Implicit PlotTo describe/draw a unit circle you might proceed

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

In[3]:= Plot@y@xD, 8x, -1, 1<Dbut you only got half the intended figure, and it is missshapen; tweaking is required:

In[4]:= Plot@8y@xD, -y@xD<, 8x, -1, 1<, AspectRatio Ø AutomaticDAlternatively, you might proceed

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

In[7]:= ParametricPlot@8x@qD, y@qD<, 8q, 0, 2 p<, AspectRatio Ø AutomaticDH*Try this also with the option omitted*L

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

Page 36: Ma Thematic A Manual

More Interesting Example

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

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

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

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

Save

‡ Graphics PrimitivesGraphics are constructed by assembly of points, lines and similar "primitives". Here follow the basic descrip-tions of some of the most essential primitive elements

In[15]:= ? Point

In[16]:= ? Line

In[17]:= ? Rectangle

In[18]:= ? Circle

In[19]:= ? Disk

In[20]:= ? Text

The basic command is Show[Graphics[{list of primitives}]]. Primitives may be individually "decorated" with options, the construction in each instance being {option,option,…,primitive}. The following command illustrates those principles:

In[21]:= Show@Graphics@[email protected], [email protected], .5<D<,[email protected], Point@81, 1.5<D<,8RGBColor@0, 0, 1D, [email protected], [email protected], -.5<D<,Circle@80, 0<, 1D,[email protected], [email protected], .75<, .75D<,8RGBColor@1, 0, 0D, [email protected], -.25<, 82, .25<D<,88RGBColor@0, 1, 0D, [email protected], -.6<, 81.7, 1.25<D<,Text@"A Design After Mondrian", 81.7, -1<D<

<D,PlotRange Ø All,AspectRatio Ø AutomaticD

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

‡ Arrows

2 Laboratory 2A.nb

Page 37: Ma Thematic A Manual

ArrowsArrows are primitive objects:

In[25]:= Graphics@8Arrow@880, 0<, 81, 1<<D<DNote that the placement of the options in the following commands:

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

In[27]:= Graphics@8RGBColor@1, 0, 0D, Arrow@880, 0<, 81, 1<<D<DThe basic command is Arrow[coordinates of tail,coordinates of head,option ,option,…], and by exercise of the options one can control the design of each arrow.

We turn now to an important graphics resource in which Mathematica draws its own arrows:

Save again.

‡ Vector FieldsAs 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`"DThe basic resource is described/illustrated below

In[29]:= ? PlotVectorField

In[30]:= Options@PlotVectorFieldD

In[31]:= vectorfield@x_, y_D := 9x4 + y4 - 6 x2 y2 - 1, 4 x y3 - 4 x3 y=H*vector field as a list of its component functions*L

In[32]:= VectorFieldPlots`VectorFieldPlot@vectorfield@x, yD, 8x, 0, 3<, 8y, 0, 3<DOpen 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

In[35]:= wagonspotential@x_, y_D := Ix2 + 3 y2M ‰1-x2-y2

Laboratory 2A.nb 3

Page 38: Ma Thematic A Manual

In[36]:= forcefield = HNeeds@"VectorFieldPlots`"D;VectorFieldPlots`GradientFieldPlot@-wagonspotential@x, yD, 8x, -2, 2<,8y, -2.5`, 2.5`<, PlotPoints Ø 20, BaseStyle Ø 8RGBColor@0, 0, 1D<DL

It would be interesting to compare the force field with the associated population of equipotentials; to that end we construct

In[37]:= equipotentials =

ContourPlot@-wagonspotential@x, yD, 8x, -2, 2<, 8y, -2.5, 2.5<,PlotPoints Ø 50,FrameTicks Ø FalseD

In[38]:= Show@ equipotentials, forcefieldD;H*If the arguments are listed in the reverse orderthen the shading masks some of the arrows. Try it.*L

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

A More Interesting Example: Electric Dipole

In[39]:= Clear@equipotentials, forcefieldD

In[40]:= dipolepotential@x_, y_D :=1

.1 + x2 + Hy - 1L2-

1

.1 + x2 + Hy + 1L2

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

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

In[42]:= dipolefield = HNeeds@"VectorFieldPlots`"D;VectorFieldPlots`GradientFieldPlot@-dipolepotential@x, yD,8x, -4, 4<, 8y, -6, 6<, PlotPoints Ø 20, AspectRatio Ø AutomaticDL

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

The preceding constructions are also possible in 3D.

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

An Example

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

4 Laboratory 2A.nb

Page 39: Ma Thematic A Manual

In[49]:= field = HNeeds@"VectorFieldPlots`"D; VectorFieldPlots`GradientFieldPlot3D@scalarfield@x, y, zD, 8x, 0, 1<, 8y, 0, 1<, 8z, 0, 1<, PlotPoints Ø 5DL

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;VectorFieldPlots`GradientFieldPlot3D@scalarfield@x, y, zD,8x, 0, 1<, 8y, 0, 1<, 8z, 0, 1<, PlotPoints Ø 5, VectorHeads Ø TrueDL

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

In[53]:= Options@ContourPlot3DD

In[54]:= surfaces = ContourPlot3D@scalarfield@x, y, zD, 8x, 0, 1<, 8y, 0, 1<, 8z, 0, 1<,Contours Ø [email protected], 0.5, 0.2D, [email protected], 0.5, 0.8D<,PlotPoints Ø AutomaticD

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

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

Save

‡ Other Graphics Available as Standard Add-onsOpen Help > Find Selected Functions... > Add-ons > Standard Packages > Graphics and you will see that graphics of types we have not discussed are at your fingertips. You will easily discover how to work those from the information/examples provided. I take explicit note of just a couple:

In[56]:= Needs@"PolyhedronOperations`"D

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

In[58]:= Show@Stellate@PolyhedronData@"Octahedron"D, 4.DDThe next example takes a bit longer; be patient:

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

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

In[63]:= Show@Graphics3D@Torus@DDDH*The @D tells Mathematica to assign default values to four adjustableparameters that control two radii and the mesh, as explained below.*L

In[65]:= ? Torus

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

In[67]:= ? MoebiusStrip

Laboratory 2A.nb 5

Page 40: Ma Thematic A Manual

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

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

We begin by introducing a population of functions of importance in connection with the quantum oscillator:

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

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

4 x2 He@n, xD

From such evidence as this

In[71]:= ‡-¶

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

In[72]:= ‡-¶

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

In[73]:= ‡-¶

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

we infer that the Y-functions are orthonormal.

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

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

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

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

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

In[79]:= state6 = Plot@Y@5, xD, 8x, -10, 10<, PlotRange Ø 8-0.7, 0.7<DWe already know how to superimpose figures:

In[80]:= Show@state1, state2, state3DHere we assemble them into an array:

In[81]:= statesarray =

Show@GraphicsGrid@88state1, state2<, 8state3, state4<, 8state5, state6<<DD

In[82]:= Show@statesarray, Frame Ø True, FrameTicks Ø NoneDThe ticks clutter up the figure; we turn them off "after the fact" as it were:

6 Laboratory 2A.nb

Page 41: Ma Thematic A Manual

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

In[83]:= Show@statesarray ê. HTicks Ø AutomaticL Ø HTicks Ø NoneLDHere is a different arrangement of the same graphical data:

In[84]:= altstatesarray =

Show@GraphicsGrid@88state1, state2, state3<, 8state4, state5, state6<<D,Frame Ø True, FrameTicks Ø NoneD

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

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

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

Laboratory 2A.nb 7

Page 42: Ma Thematic A Manual

Physicist's Introduction to MathematicaLaboratory 2Part B

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

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

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

4 x2 He@n, xD

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

In[4]:= AnimateBPlotB12

Y@2, xD2 + Y@2, xD Y@3, xD CosB 1

20H2 pL nF +

1

2Y@3, xD2,

8x, -10, 10<, PlotRange Ø 80, 0.5<, Ticks Ø NoneF, 8n, 0, 19<F

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

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

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

In[5]:= AnimateBShowBGraphicsB:

:RGBColor@0, 0, 1D, DiskB:2 + CosB2 p

30 nF, 0>, .1F>, H*mass point*L

[email protected], [email protected], -.5<, 80, .5<D<, H*left wall*[email protected], Rectangle@84, -.5<, 84.1, .5<D<, H*right wall*L:RGBColor@1, 0, 0D, RectangleB:0, -.02 + .01 CosB2 p

30 nF>,

:1.9 + CosB2 p

30 nF, .02 - .01 CosB2 p

30 nF>F>H*rubber band*L

>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."

Page 43: Ma Thematic A Manual

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

ShowBGraphicsB:RGBColorB1 + CosA p

20 nE2

2,1 + SinA p

20 nE2

2, 0F, Disk@80, 0<, 1D>,

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

Plot3DBSinBx * y + SinB p

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

Save.

Built into Mathematica is a valuable resource which we illustrate as it relates to the following surface:

In[9]:= wave = Plot3D@Sin@x * yD, 8x, 0, 3<, 8y, 0, 3<, Axes Ø NoneDH*Here we have recreated the first frame in the preceding movie.*LH*The AxesØNone is essential to the success of what we are about to do.*L

‡ Exporting Mathematica Graphics to TeXClick on a cell containing the graphic to Select it: it will acquire a frame with handles. Open File > Save Selection As… > PDF… . From there it can be imported (by any of a variety of commands) into your TEX document.

Relatedly…suppose you have done a calculation~for example

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

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

In[15]:= TeXForm@%Dautomatically translates the output into TEX code, which can be pasted directly into your document.

2 Laboratory 2B.nb

Page 44: Ma Thematic A Manual

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

In[16]:= ? TeXForm

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

Installing Standard Add-on Packages

These, as you have already seen, supply Mathematica with some of its most valuable resources. One should take steps to become familiar with them.

A safer procedure~which we have many times used already~is to enter a command of the form Needs["DisÖ

creteMath`CombinatorialFunctions`"], which writes into the kernel only when it is proper/appropriate to do so.

In[17]:= ? Needs

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

Some Miscellaneous Resources

‡ Physical Constants

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

In[19]:= PlanckConstant

In[20]:= SpeedOfLight

In[21]:= EarthRadius

In[22]:= FineStructureConstant

In[23]:= 1 ê %

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

Laboratory 2B.nb 3

Page 45: Ma Thematic A Manual

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

‡ Conversion from One System of Units to Another

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

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

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

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

In[28]:= Convert@SolarMass, AtomicMassUnitD

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

In[30]:= CGS@65 Mile ê HourDSee the Browser for further examples, discussion. We will return also to this topic in Laboratory 5.

‡ Calendar

In[31]:= Needs@"Calendar`"DTanja was born on 16 December 1968. From

In[32]:= DayOfWeek@81968, 12, 16<DI am reminded that she was born on a Monday. From

In[33]:= DaysBetween@81968, 12, 16<, 82000, 6, 8<DI learn that as of the date of writing she was 11,497 days old, and that

In[34]:= Convert@11 497 Day, SecondDshe is approaching her one billionth birthsecond. That, I find…

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

In[36]:= NB312 500 Day27

F

In[37]:= DaysPlus@81968, 12, 16<, 11 574D…will actually occur on the August 24, 2000, when she will be

In[38]:= Convert@1 000 000 000 Second, YearD êê N

old.

‡ Maps

4 Laboratory 2B.nb

Page 46: Ma Thematic A Manual

Maps

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

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

In[41]:= World

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

Save.

Make sure that sound is on.

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

In[42]:= ? Play

In[43]:= Play@Sin@2 p 440 tD, 8t, 0, 3<DThe sonogram is often uninformative, but occasionally it does provide a useful "second handle" on your acous-tic experience:

Beats

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

Twang

In[45]:= PlayBSin@2 p 440 tD ‰-

t

0.5, 8t, 0, 3<F

Save.

Perfect Chords: Why Do They Sound So Unmusical?

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

1 tF ‰

-t

0.5, 8t, 0, 3<F

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

2 tF ‰

-t

0.5, 8t, 0, 3<F

Laboratory 2B.nb 5

Page 47: Ma Thematic A Manual

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

3 tF ‰

-t

0.5, 8t, 0, 3<F

In[49]:= temperedthird = PlayBKSin@2 p 440 tD + SinB2 p 440 25

12 tFO ‰-

t

0.5, 8t, 0, 3<FH* Note the occurence of beats in the harmonics *L

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

An Non-acoustic Application of Audio

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

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

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

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

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

Save.

Additional audio resources are made available this way:

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

In[53]:= ? Waveform

In[54]:= Options@WaveformD

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

In[56]:= Show@%D;

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

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

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

Construction of a Short Tempered Scale

In[59]:= 22

12 440 êê N

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

6 Laboratory 2B.nb

Page 48: Ma Thematic A Manual

In[61]:= 24

12 440 êê N

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

In[63]:= 25

12 440 êê N

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

In[65]:= Show@sinusoidA, triangleB, squareCsharp, sawtoothDDAlso available in the Audio package are

In[66]:= ? AmplitudeModulation

In[67]:= ? RingModulation

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

In[69]:= ? FrequencyModulation

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

Save.

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

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

In[72]:= ? Scale

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

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

You can see the difference; could you hear it?

Mathematica provides means to undertake sophisticated analysis of images and signals. There are many references.

Laboratory 2B.nb 7

Page 49: Ma Thematic A Manual

Finding Things in Notebooks

We have learned to turn off graphics in order to conserve memory. This, unfortunately, makes it a little diffi-cult to discover~when you want it again~where in the notebook the in question graphic occurred. Descriptive text, if inserted on the occasion, helps…but in a long notebook that can take awhile to scan the text. Happily, there is a better way:

Suppose you have interest in returning to the discussion of quantum oscillators. Open Edit >Find> Find… (or simply hit Ì-F ), activate the Ignore case and Wrap around buttons, write "quantum" under Search for: and hit the Find All button, and use Next to advance from occurrence to occurrence until you find the "quantum" you had in mind.

Or suppose (as happened to me) you use a "GrayScale" option in an effort to make a gray line, and find that it does not work. But earlier we did have success; how did we do it? A search from "gray" leads immediately to In[21], where we discover that the correct term is GrayLevel.

The Help menu provides, in fact, many useful resources additional to the one I have described.

Save.

8 Laboratory 2B.nb

Page 50: Ma Thematic A Manual

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

Laboratory 3Part A

Algebra

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

Mathematica looks upon Hx + yL7as a primitive object.

In[2]:= Hx + yL7

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

In[3]:= ? Expand

In[4]:= Options@ExpandDHere follow some examples:

In[5]:= ExpandAHx + yL7E

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

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

Standardly the powers xn are in ascending order. The command //TraditionalForm reverses the order and adjusts the font.

In[8]:= ExpandAH1 + xL3 + H2 + xL3 + H1 + yL2, 1 + xEH*Expands only the part containing the stated pattern*L

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

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

Page 51: Ma Thematic A Manual

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

In[9]:= ? Together

In[10]:= ? Apart

In[11]:= TogetherBab

+c

dF

In[12]:= ApartBb c + a d

b dF

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

In[13]:=a

b+c

dêê Together

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:

In[15]:= ApartB 1

Hx - aL Hx - bLF

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

In[16]:= PlotB 1

Hx - 1L Hx - 2L, 8x, 0, 3<F;

In[17]:=1

Hx - 1L Hx - 2L êê Apart

In[18]:= PlotB: 1

-2 + x, -

1

-1 + x>, 8x, 0, 3<,

PlotStyle Ø 8RGBColor@1, 0, 0D, RGBColor@0, 0, 1D<F;

Here are some slightly more complicated examples:

2 Laboratory 3A.nb

Page 52: Ma Thematic A Manual

In[19]:=1

x2 - a2êê Apart

In[20]:=1

x2 + a2êê Apart

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.

In[21]:= ApartB H1 + xL H2 + xL H7 + xLH1 + xL H3 + xL I1 + 2 x + 3 x2M

F

One should be aware also of the following commands:

In[22]:= ? Cancel

In[23]:= ? ExpandDenominator

In[24]:= ? ExpandNumerator

In[25]:= CancelB H1 + xL H2 + xL H7 + xLH1 + xL H3 + xL I1 + 2 x + 3 x2M

F

In[26]:= ExpandDenominatorB H1 + xL H2 + xL H7 + xLH1 + xL H3 + xL I1 + 2 x + 3 x2M

F

In[27]:= ExpandNumeratorB H1 + xL H2 + xL H7 + xLH1 + xL H3 + xL I1 + 2 x + 3 x2M

F

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

One should not confuse the number-theoretic command

In[28]:= ? FactorInteger

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

In[29]:= ? Factor

In[30]:= Options@FactorDthough both~unlike the algebraic commands considered thus far~display a preoccupation with the integers (or, by extension, with their complex generalizations, the "Gaussian integers").

In[31]:= FactorA17 x6 + 3 x5 + 274 x4 + 48 x3 - 3793 x2 - 675 x - 450E

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

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

The example

Laboratory 3A.nb 3

Page 53: Ma Thematic A Manual

The example

In[33]:= FactorAx2 - 9E

In[34]:= % êê Expand

serves to expose the sense in which Factor and Expand are inverse commands (undo each other); enlarging upon that example, we have

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

In[36]:= % êê Expand

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

Save.

‡ Finding the Roots of a PolynomialThe celebrated Fundamental Theorem of Algebra (Gauss) asserts that every polynomial of degree n (coefficients real or complex) possesses n roots (real or complex). Those can be discovered by means of the following commands:

In[37]:= ? Solve

In[38]:= ? NSolve

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

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

The quadratic formula has been known for since antiquity

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

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

In[42]:= SolveA x3 + b x + c ã 0, xE

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

All efforts to solve the quintic (which everyone expected to be difficult) failed…for what Galois and Abel showed (early 19th Century) to be this very good reason: solution (in the sense of the preceding formulae) is impossible, except in special cases. Mathematica has this to say in the general case:

In[44]:= SolveA x5 + w x3 + a x2 + b x + c ã 0, xE

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

4 Laboratory 3A.nb

Page 54: Ma Thematic A Manual

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

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

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

Here is a more acccurate version of the same statement:

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

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

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

ListPlot@Map@8Re@Ò1D, Im@Ò1D< &, pointsD,options, AxesLabel Ø 8"Re", "Im"<D

and works like this:

In[49]:= ComplexListPlot@8-1 + Â, 2 + Â, 1 - 2 Â<, PlotStyle Ø [email protected];We now use that tool to plot the complex numbers that arise as roots of a polynomial:

In[50]:= RootPlot@expr_, x_D :=

ComplexListPlot@x ê. N@Solve@expr ã 0, xDD,AspectRatio Ø Automatic, PlotStyle Ø [email protected]

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

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

Another example:

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

Save.

When we plot the polynomial we see the real roots as axis-crossings, but only an obscure hint of the complex roots:

In[53]:= PlotAx6 - 2 x2 + 4 x + 4, 8x, -1.5, 1.5<E;

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

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

The figures are so similar because

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

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

and

Laboratory 3A.nb 5

Page 55: Ma Thematic A Manual

and

x17 - 1

are very closely related:

In[56]:= SeriesBx17 - 1

x - 1, 8x, 0, 17<F

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

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

The Little Example Upon Which I Hang a Digression

The roots of

x4 -15

9 x2 + 1 ã 0

are all complex

In[58]:= NBSolveBx4 -15

9 x2 + 1 ã 0, xFF êê TableForm

In[59]:= RootPlotBx4 -15

9 x2 + 1, xF;

and don't show up in graphs of the form

In[60]:= PlotBx4 -15

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

That observation motivates the following…

Solving Systems of Simultaneous Equations

Generic Pair of Coupled Linear Equations

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

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

6 Laboratory 3A.nb

Page 56: Ma Thematic A Manual

Solution of an Inhomogeneous Linear Triple

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

Nonlinear Pair

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

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

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

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

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

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

solution. See how Mathematica conveys that information.*LAnd here it does the job, but publishes a disclaimer:

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

Trigonometry

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

In[93]:= ? TrigExpand

In[94]:= ? TrigFactor

In[95]:= ? TrigReduce

In[96]:= ? TrigToExp

In[97]:= ? ExpToTrig

A few examples will make clear what they do:

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

Laboratory 3A.nb 7

Page 57: Ma Thematic A Manual

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

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

In[101]:= TrigExpand@%D

In[102]:= Simplify@%D

In[103]:= TrigReduceACos@aD3E

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

In[105]:= TrigFactor@%D

In[106]:= TrigToExpASin@aD3E

In[107]:= ExpToTrigA‰Â qE

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

With the aid of the preceding commands one can~with experience~reconstruct and enlarge upon the standard lists of trigonometric identities. Experience is required because any given trigonometric expression can be written in a zillion ways, and one must learn how to tell Mathematica the goal one has in mind.

And in the latter regard one must be braced for some surprises. For example: suppose~with

In[109]:= TrigExpandAHSin@aD + Sin@bDL2E

in mind~we ask for

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

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

In[111]:= [email protected] tD + [email protected] tDL2E

Save

Some Elementary Physical Applications

Superimposed harmonic signals of the unequal amplitude but nearly the same frequency yield a signal of the form:

In[112]:= compositesignal@t_D := Sin@100 tD +1

2 Sin@102 tD

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

In[113]:= Plot@compositesignal@tD, 8t, 0, 5<Dof which this provides (at augmented frequency) an audio representation:

8 Laboratory 3A.nb

Page 58: Ma Thematic A Manual

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

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

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

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

But if the signal is fed into an intensity detector we see/hear something quite different:

In[116]:= intensity@t_D := Sin@100 tD +1

2 Sin@102 tD

2

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

In[118]:= PlayB Sin@100 µ 2 p tD +1

2 Sin@102 µ 2 p tD

2

, 8t, 0, 3<F

From

In[119]:= TrigReduceB [email protected] tD +1

2 [email protected] tD

2

F

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

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

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

Laboratory 3A.nb 9

Page 59: Ma Thematic A Manual

0 0 0 00 0 0 00 0 0 00 0 0 0

and

0 Ñ Ñ ÑÑ 0 Ñ ÑÑ Ñ 0 ÑÑ Ñ Ñ 0

with a single keystroke. Often useful also is the command

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

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

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

In[122]:= rowvector = H a1 a2 a3 L

columnvector =b1b2b3

matrix =m11 m12 m13m21 m22 m23m31 m32 m33

Mathematica reveals here its instinct to display matrices as lists of lists…which is, however, easily overridden:

In[125]:= rowvector êê MatrixForm H*Compare that with the following:*Lrowvector êê TraditionalForm

In[127]:= columnvector êê MatrixForm

In[128]:= matrix êê MatrixForm

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

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

In[129]:= M = K a bc d

O

In[130]:= Tr@MD

In[131]:= Det@MD

In[132]:= H Ñ Ñ Ñ L

10 Laboratory 3A.nb

Page 60: Ma Thematic A Manual

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

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

In[134]:= Dimensions@rowvectorDDimensions@columnvectorDDimensions@matrixDMatrix multiplication is accomplished not with a * but with a . as illustrated below:

In[137]:= A = K a11 a12a21 a22

O

B = K b11 b12b21 b22

O

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

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

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

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

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

In[141]:= % êê MatrixForm

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

The commands rowvector.rowvector and columnvector.columnvector are meaningless (except in the one-dimensional case), as Mathematica is quick to remind you:

In[143]:= rowvector.rowvector

In[144]:= columnvector.columnvector

But the object (actually a simple list)

In[145]:= eithervector = 8c1, c2, c3<can in some contexts be used as if it were "simultaneously row/column:"

In[146]:= eithervector.eithervector

In[147]:= matrix.eithervector

In[148]:= eithervector.matrix

Because matrix multiplication is a bit quirky, one must take special steps to raise a square matrix to a power; this is accomplished with the assistance of

In[149]:= ? MatrixPower

In[150]:= S = K 0 -11 0

O

Laboratory 3A.nb 11

Page 61: Ma Thematic A Manual

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

In[152]:= R = ‚n=0

6 1

n! qn MatrixPower@S, nD êê MatrixFormH*Mathematica

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

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

which we recognize to be a rotation matrix:

In[154]:= Simplify@Transpose@RD == Inverse@RDDActually, Mathematica provides a command which eliminates the guess work, and is very useful in a great variety of pure/applied contexts:

In[155]:= ? MatrixExp

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

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

In[157]:= ? Outer

is opaque because "outer multiplication" is such a general notion. As physicists we have common need only of the simplest instances of outer multiplication. Recalling that by prior definition

In[158]:= A êê MatrixFormB êê MatrixForm

Out[158]//MatrixForm=

K a11 a12a21 a22

OOut[159]//MatrixForm=

K b11 b12b21 b22

O

we construct

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

K a11 b11 a11 b12a11 b21 a11 b22

O K a12 b11 a12 b12a12 b21 a12 b22

O

K a21 b11 a21 b12a21 b21 a21 b22

O K a22 b11 a22 b12a22 b21 a22 b22

O

which has the design

K a11 B a12 Ba21 B a22 B

O

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

12 Laboratory 3A.nb

Page 62: Ma Thematic A Manual

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

In[161]:=1 xx2 x3

+ a êê MatrixForm

In[162]:= ‡ 1 xx2 x3

„x êê MatrixForm

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

In[163]:= M êê MatrixForm

is defined

In[164]:= DetBK a - x bc d - x

OF

In Mathematica it results from the command

In[165]:= CharacteristicPolynomial@M, xDThe 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@2Dnullmatrix = K 0 0

0 0O

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

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

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

but Mathematica provides a better way:

In[170]:= ? Eigenvalues

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

Thus far we have asked Mathematica to do matrix-theoretic things we could as easily have done by hand. The power of Mathematica is more clearly evident in higher-dimensional situations. To have some representative material to work with, we construct a 5 by 5 matrix with random real-valued elements:

In[172]:= randomrealmatrix = 8RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D,RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D,RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D,RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D,RandomReal@8-2, 2<, 5, WorkingPrecision Ø 6D<

In[173]:= % êê MatrixForm

In[174]:= symmetricpart =1

2 Hrandomrealmatrix + Transpose@randomrealmatrixDL

Laboratory 3A.nb 13

Page 63: Ma Thematic A Manual

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@randomrealmatrixDWe find that the eigenvalues are typically complex, but occur in conjugate pairs, and that in odd-dimensional cases at least one is necessarily real:

In[177]:= Eigenvalues@randomrealmatrixD êê TableForm

We plot the distribution of those complex eigenvalues:

In[178]:= CharacteristicPolynomial@randomrealmatrix, xDLook similary to the real symmetric part of the preceding matrix; we find that all the eigenvalues are real:

In[180]:= Eigenvalues@symmetricpartD êê TableForm

In[181]:= CharacteristicPolynomial@symmetricpart, xD

Save

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

In[183]:= randomcomplexmatrix =

8RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D,RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D,RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D,RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D,RandomComplex@8-2 - 2 Â, 2 + 2 Â<, 5, WorkingPrecision Ø 6D<

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

Construct also the hermitian part of that matrix:

In[184]:= hermitian =1

2 Hrandomcomplexmatrix + Transpose@Conjugate@randomcomplexmatrixDDL

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

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

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

In[187]:= ? Chop

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

14 Laboratory 3A.nb

Page 64: Ma Thematic A Manual

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

which is possible iff "number" is in fact one or another of the eigenvalues of the matrix. This can be accom-plished by the command

In[192]:= ? Eigenvectors

(which is available as a button on the Matrix Operations palette) but it is usually more informative/efficient to use

In[193]:= ? Eigensystem

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

In[194]:= tracelesssymmetric = K 1 22 -1

O;

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

We use that information to define

In[196]:= eigenvalue1 = - 5

eigenvector1 =1- 5

2

1

eigenvalue2 = 5

eigenvector2 =1+ 5

2

1

and find that indeed

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

Ignore the cautionary quibble and proceed:

In[201]:= Simplify@%D

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

The eigenvectors are, as presented, not normalized

In[203]:= squaredlength1 = [email protected] êê N

In[204]:= squaredlength2 = [email protected] êê N

In[77]:= a1 = GraphicsB:ArrowB:80, 0<, :12

J1 + 5 N, 1>>F>F;

In[78]:= a2 = GraphicsB:ArrowB:80, 0<, :12

J1 + 5 N, 1>>F>F;

In[79]:= Show@a1, a2DWe see the eigenvectors to be orthogonal, which is confirmed by the observation that

Laboratory 3A.nb 15

Page 65: Ma Thematic A Manual

In[207]:= dotproduct = [email protected] êê Simplify

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

Save, then continue to Part B

16 Laboratory 3A.nb

Page 66: Ma Thematic A Manual

Physicist's Introduction to MathematicaLaboratory 3Part B

Calculus

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

‡ Simple definite/indefinite integrals

In[2]:= ? Integrate

In[3]:= ‡ Sech@xD2 „x H*A typical indefinite integral*L

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

In[6]:= ‡-3

3

Sech@xD2 „x H*A typical definite integral*L

In[7]:= N@%, 25DMathematica can often manage singular integrands without difificulty:

In[8]:= ‡-3

3 1

x2 „x

In[9]:= PlotB 1

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

In[10]:= ‡-¶

x

DiracDelta@y - 1D „y

In[11]:= Plot@UnitStep@-1 + xD, 8x, -3, 3<Dand is even capable of some "singular differentiation":

In[12]:= ∂x UnitStep@-1 + xDBuilt 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:

Page 67: Ma Thematic A Manual

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:

In[13]:= ‡0

1

ArcTan@xD „x

‡ Numerical integrationBut from

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

we see that the definite integral in question is a perfectly reasonable thing to ask for~a certain number. It can be got this way:

In[15]:= ? NIntegrate

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

‡ Functions defined by integralsOften Mathematica responds in ways you might not think are immediately informative:

In[17]:= ‡ CosAx2E „x

Mathematica is telling you that your obligation at this point is to learn some mathematics! Specifically, to learn about Fresnel functions. As first steps toward that objective you might proceed

In[18]:= ? FresnelC

In[19]:= Plot@FresnelC@xD, 8x, 0, 6<, PlotRange Ø AllDFinally, 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 := ‡0

t

g@uD „u + v0

y@t_D := ‡0

t

v@wD „w + y0

In[23]:= g@tDv@tDy@tD

Less trivially: the function defined as follows

In[26]:= q@xD := ‡0

x 1

1 - x2

„x

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

2 Laboratory 3B.nb

Page 68: Ma Thematic A Manual

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

In[27]:= Sin@q@xDD

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

‡ Multiple integralsThe 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

In[29]:= ‡0

1

‡0

x

Sin@x yD „y „x

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:

In[30]:= ‡0

x

Sin@x yD „y

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:

In[31]:= PlotBEvaluateB1x

-CosAx2E

x, 8x, 0, 1<F, PlotRange Ø AllF

So we proceed numerically:

In[32]:= NIntegrateB1x

-CosAx2E

x, 8x, 0, 1<F

Save.

‡ Ordinary & partial differentiationThe Basic Input palette provides ∂„‡ and ∂„ ,„‡ buttons that work this way:

In[33]:= ∂xSinAx2E + CosAy2E

1 - x2 - y2

In[34]:= ∂ySinAx2E + CosAy2E

1 - x2 - y2

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

Laboratory 3B.nb 3

Page 69: Ma Thematic A Manual

In[35]:= ∂x,ySinAx2E + CosAy2E

1 - x2 - y2

In[36]:= ∂y,xSinAx2E + CosAy2E

1 - x2 - y2

If you use the ∂Ñ É button to create

In[37]:= ∂8x,5<x10 H*you get the 5th derivative:*LThe 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

In[39]:= DBSinAx2E + CosAy2E

1 - x2 - y2, xF

In[40]:= DBSinAx2E + CosAy2E

1 - x2 - y2, x, yF

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

In[42]:= f@x_D :=SinAx2E

1 - x2

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

In[44]:=SinAx2E

1 - x2' H*...but not the bare expression:*L

It is easy to ask for the value assumed by f'[x] when x is assigned a particular value

In[45]:= f'@.5Dand we can use multiple primes to multiply differentiate:

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

4 Laboratory 3B.nb

Page 70: Ma Thematic A Manual

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

Alternatively we might have commanded

In[50]:= D@g@xD, xDD@g@xD, 8x, 2<DD@g@xD, 8x, 3<D

Dummy Functions

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

In[53]:= Clear@f, gD

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

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

In[55]:= ∂xf@xDg@xD H*Quotient Rule*L

In[56]:= Together@%D

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

In[58]:= Simplify@%D

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

In[60]:= D@f@g@xDD, 8x, 2<DH*Higher-order differentiation of a composite function:*L

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

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

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

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

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

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

Laboratory 3B.nb 5

Page 71: Ma Thematic A Manual

In[66]:= DB‡0

x

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

In[67]:= ‡0

x

D@f@uD, uD „u

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

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

In[69]:= D@f@x, g@x, yDD, x, yDetc. Note the notational device used by Mathematica to tell us what has been partially differentiated with respect to what.

Save.

Implicit Differentiation

This technique is often quite useful, though it is my impression that it is no longer taught in introductory calcu-lus courses.

Suppose we know of y[x] only that

In[70]:= Clear@x, y, aD

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

Then

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

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

In[73]:= Solve@2 x - 10 y@xD - 10 x y£@xD + 2 y@xD y£@xD ã 0, y£@xDDTo find the 2nd derivative y''[x] we would proceed

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

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

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

H5 x - y@xDL2-

-1 + 5 p

5 x - y@xD

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

In[78]:= Simplify@%DBut it was announced at the outset that

6 Laboratory 3B.nb

Page 72: Ma Thematic A Manual

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

so we have finally

In[80]:= y''@xD ==24 a2

Hy - 5 xL3

Maxima & Minima

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

In[81]:= Clear@fD

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

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

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

In[85]:= N@%DThose 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.

In[87]:= Plot@f@xD, 8x, -4, 4<,Epilog Ø [email protected], Hue@1D, Map@Point, extremaD<D

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

‡ Limits & SeriesThese, of course, are distinct but closely interrelated topics; I lump them together partly for that reason, and partly because the Calculus palette juxtaposes the buttons that produce

Limit@‡, Ñ Ø ÑDSeries@‡, 8Ñ, Ñ, Ñ<D

In[88]:= ? Limit

In[89]:= ? Series

First Example

Laboratory 3B.nb 7

Page 73: Ma Thematic A Manual

First Example

In[90]:= Clear@fD

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

x

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

In[92]:= Plot@f@xD, 8x, -6 p, 6 p<, PlotRange Ø AllDwe see that the function is perfectly well-behaved there, and are not surprised to obtain

In[93]:= Limit@f@xD, x Ø 0DExpansion about the origin shows how this result is achieved:

In[94]:= Series@f@xD, 8x, 0, 4<DAlso of interest is the statement

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

Second Example

Look now to the function

In[96]:= Clear@gD

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

x

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

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

In[100]:= Limit@g@xD, x Ø 0, Direction Ø 1D

Third Example

While the function

‰-x

has well-defined limits

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

the function

8 Laboratory 3B.nb

Page 74: Ma Thematic A Manual

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

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

Some Series~Familiar & Less Familiar

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

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

In[107]:= SeriesB 1

1 - x, 8x, 0, 10<F

In[108]:= SeriesB 1

1 - x LogB 1

1 - xF, 8x, 0, 10<F

In the latter connection we note that

In[109]:= TableB‚k=1

n 1

k, 8n, 1, 10<F

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

In[110]:= SeriesB‚k=1

¶ Cos@k xDk2

, 8x, 0, 4<F

In[111]:= Simplify@%DJust as interesting integrals are sometimes taken to define numbers/functions, so are interesting series. The following series serves to define the Bernoulli numbers

In[119]:= SeriesB t

‰t - 1, 8t, 0, 10<F

In[120]:= TableBBernoulliB@nDn!

, 8n, 0, 10<F

while this celebrated series

In[121]:= ‚n=1

n-z

serves to define the Riemann zeta function:

In[122]:= ? Zeta

Save.

Laboratory 3B.nb 9

Page 75: Ma Thematic A Manual

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

Laboratory 4

Solving Ordinary Differential Equations

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

F@x@tD, x'@tD, x''@tD, ...D ã 0

together with prescribed initial/boundary conditions. Newton's 2nd Law provides the classic case in point: it presents the problem of dynamical motion as the problem of solving

m x''@tD ã F@x@tDDInitial conditions : x@t0D ã x0 and x'@t0D ã v0

or, more generally, of solving

m x''@tD ã Fx@x@tD, y@tD, z@tDDm y''@tD ã Fy@x@tD, y@tD, z@tDDm z''@tD ã Fz@x@tD, y@tD, z@tDDSix initial conditions required

which comprise a coupled system of 2nd order ODEs.

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

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

Page 76: Ma Thematic A Manual

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…

• Mathematica knows all the tricks.

• Mathematica permits a simple, unified approach to the solution of ODEs.

In[2]:= ? DSolve

In[3]:= ? NDSolve

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

‡ Exponential Population Growth

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

P'@tD ã a P@tDThe general solution is obvious, but let us ask Mathematica to do the work:

In[4]:= DSolve@P'@tD ã a P@tD, P@tD, tDThe output is a replacement list (in this case, a one-element list). C[1] is the name Mathematica gives to the arbitrary constant of integration.

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

A Short Digression~Removing the Braces

The outer { }'s sometimes gets in the way (as we will soon enough see); to strip it away we might command

In[5]:= DSolve@P'@tD ã a P@tD, P@tD, tD êê TableForm

but in more complicated situations that proves not to be such a good idea; if tried in connection with the follow-ing coupled pair of first-order ODEs (system of second order: note the appearance of both C[1] and C[2] in the output)

In[6]:= DSolve@8p'@tD ã a q@tD, q'@tD ã b p@tD<, 8p@tD, q@tD<, tD êê TableForm

we find that the output overextends the right side of the page. A better procedure, makes use of these two commands:

In[7]:= ? First

In[8]:= ? ReplaceAll

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

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

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

2 Laboratory 4A.nb

Page 77: Ma Thematic A Manual

In[11]:= 8tom, sally, harry<P2TReplaceAll works like this:

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

In[12]:= :a, b, x,1

1 + x, c> ê. x Ø sally

So in place of

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

In[14]:= First@DSolve@P'@tD ã a P@tD, P@tD, tDDto discard the distracting outer bracket, and

In[15]:= solution = P@tD ê. First@DSolve@P'@tD ã a P@tD, P@tD, tDDto display the solution of the ODE in question. From

In[16]:= D@solution, tD ã a solution H* a is here not an article, but a factor *Lwe confirm that it is in fact a solution.

In our more complicated second example (the coupled system) we write

In[17]:= 8psol, qsol< = 8p@tD, q@tD< ê.First@DSolve@8p'@tD ã a q@tD, q'@tD ã b p@tD<, 8p@tD, q@tD<, tDD

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

Here ends this digression.

Exponential Population Growth Resumed: the Slope Field Concept

The equation

y'@xD ã f@x, yDtells 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

Laboratory 4A.nb 3

Page 78: Ma Thematic A Manual

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

: 1

1 + P2,

P

1 + P2>, 8t, -2, 2<, 8P, 0, 8<, AspectRatio Ø AutomaticF

We now construct the general solution of the preceding ODE

In[21]:= P@tD ê. First@DSolve@P'@tD ã P@tD, P@tD, tDDand look to the particular solution that arises from setting C[1] = 1

In[22]:= % ê. C@1D Ø 1

We ask Mathematica to plot that solution

In[23]:= sol = PlotA‰t, 8t, -2, 2<, AspectRatio Ø Automatic,

PlotStyle Ø 8RGBColor@1, 0, 0D, [email protected]<E

and to superimpose the two preceding figures

In[24]:= Show@slopefield, solDThis shows quite clearly how the red solution "threads through" the slope field, and it becomes evident to the eye what the solution that passes through any specified point would look like.

Variants of the idea just illustrated are of very widespread utility, and often help one to grasp the qualitative essentials of complex situations.

Save.

‡ Limited Population Growth: the "Logistic Model"Modify the right side of the preceding ODE so as to have

P'@tD ã P@tD H5 - P@tDLP@0D = 1

From

In[25]:= Plot@P H5 - PL, 8P, 1, 9<D;we see that the population grows if P < 5, becomes steady at P = 5, diminishes if P > 5. Proceeding

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

In[27]:= p@tD ê. First@DSolve@8logistic ã 0, p@0D ã 1<, p@tD, tDDwe obtain the particular population curve in which we have a declared interest. We plot it:

4 Laboratory 4A.nb

Page 79: Ma Thematic A Manual

In[28]:= logisticpopulation = PlotB 5 ‰5 t

4 + ‰5 t, 8t, -2, 3<,

PlotRange Ø All, PlotStyle Ø 8RGBColor@1, 0, 0D, [email protected]<,AxesLabel Ø 8Time, Population<F

Next, we plot the associated slope field

In[29]:= logisticslopefield = Needs@"VectorFieldPlots`"D;

VectorFieldPlots`VectorFieldPlotB: 1

1 + Hp H5 - pLL2,

p H5 - pL

1 + Hp H5 - pLL2>,

8t, -2, 3<, 8p, 0, 6<, AspectRatio Ø AutomaticF

and superimpose our particular solution on that slope field:

In[30]:= Show@logisticslopefield, logisticpopulationD

Save.

‡ Harmonic OscillatorThe equation of physical interest reads

m x''@tD = -m w2 x@tDand in a typical special case (drop the m and set w =3) can be brought to the form

x''@tD = -32 x@tDWe declare an interest in motion that arises from the initial conditions

x@0D = 0x'@tD = 1

Here are commands that produce a diagram of a mass attached to a spring:

REMARK: There is much of value to be learned from the following commands (concerning which Abell & Braselton supply explanatory remarks), but today is not the day.

Laboratory 4A.nb 5

Page 80: Ma Thematic A Manual

In[31]:= zigzag@8a_, b_<, 8c_, d_<, n_, e_D := ModuleB8length, points, pairs<,length = d - b;

points = TableBb +i length

n, 8i, 1, n - 1<F;

pairs = TableA9a + e H-1Li, pointsPiT=, 8i, 1, n - 1<E;PrependTo@pairs, 8a, b<D; AppendTo@pairs, 8c, d<D;Line@pairsDF

In[32]:= typicalposition = 3 ê 4;

In[34]:= Show@Graphics@8zigzag@80, typicalposition<, 80, 2<, 40, 0.05D,[email protected], 8RGBColor@1, 0, 0D, Point@80, typicalposition<D<,[email protected], 0.75<, 80.3, 0.75<<D, [email protected], 0<, 80.2, 0.2<<D,[email protected], 0.375<, 80.2, 0.75<<D, Text@"x", 80.2, 0.3<D,[email protected], [email protected], 2<, 80.5, 2.2<D<<D,

PlotLabel Ø Style@"Simple Harmonic Oscillator",FontFamily Ø "Times-Bold", FontSize Ø 16D,

Axes Ø Automatic, AxesStyle Ø [email protected], Ticks Ø None,PlotRange Ø 88-1, 1<, 8-2, 2.2<<, AspectRatio Ø 1D

We ask Mathematica to solve the equation of motion (which is an ODE of now second order), subject to the prescribed initial conditions:

In[35]:= harmonicoscillator =

x@tD ê. FirstADSolveA9x''@tD ã -32 x@tD, x@0D ã 0, x'@0D ã 3=, x@tD, tEE

There are several ways to display that information; the most obvious is to simply plot it

In[36]:= Plot@harmonicoscillator, 8t, 0, 10<, AxesLabel Ø 8"time", "x"<DOr we might animate the diagram:

In[37]:= simpleoscillator@t_D :=

Show@Graphics@8zigzag@80, harmonicoscillator<, 80, 2<, 40, 0.05D, [email protected], 8RGBColor@1, 0, 0D, Point@80, N@harmonicoscillator HtLD<D<,

[email protected], [email protected], 2<, 80.5, 2.2<D<<D,PlotLabel Ø Style@"Animated Simple Harmonic Oscillator",FontFamily Ø "Times-Bold", FontSize Ø 16D,

Axes Ø Automatic, AxesStyle Ø [email protected], Ticks Ø None,PlotRange Ø 88-1, 1<, 8-2, 2.2<<, AspectRatio Ø 1D

In[38]:= AnimateBsimpleoscillator@tD, :t, 0,2 p

3 29

30,2 p

3 1

30>F

Select any frame, then double click to watch the movie.

Save. Then close this notebook, quit and restart Mathematica, and open Part B.

6 Laboratory 4A.nb

Page 81: Ma Thematic A Manual

Physicist's Introduction to MathematicaLaboratory 4Part B

‡ Damped Harmonic OscillatorThe standard model of a damped oscillator can be described

m x''@tD = -2 m b x'@tD - m w2 x@tDwhere 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[3]:= dampedmotion@t_, b_D := -‰t -b- b2-32

3

2 b2 - 32+

‰t -b+ b2-32

3

2 b2 - 32

In[4]:= dampedmotion@t, 1 ê 2DWe fuss a bit to bring this result to its most transparently simple form

In[5]:= ExpToTrigB% ‰1

2 tF êê Simplify

~REMARK: It would have been quicker simply to go back to the beginning, and ask for

In[6]:= x@tD ê.FirstBDSolveB:x''@tD ã -2

1

2x'@tD - 32 x@tD, x@0D ã 0, x'@0D ã 3>, x@tD, tFF

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:

In[7]:= PlotB:‰-1

2 t 6 SinB 35 t

2F

35, ‰-

1

2 t

6

35, -‰-

1

2 t

6

35>, 8t, 0, 10<,

PlotStyle Ø 88<, RGBColor@0, 0, 1D, RGBColor@0, 0, 1D<,PlotRange Ø 8-1, 1<F

To show the effect of increasing b in the underdamped regime we create an animation:

Page 82: Ma Thematic A Manual

Physicist's Introduction to MathematicaLaboratory 4Part C

‡ Damped PendulumWe look to the illustrative equation

q''@tD ã -q'@tD - 32 Sin@q@tDDMathematica thinks for awhile, then informs us that it is unable to supply an analytical solution

In[2]:= DSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 3=, q@tD, tE

so we proceed numerically:

In[3]:= NDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 3=, q@tD, 8t, 0, 10<E

Or better~we define:

In[4]:= dampedpendulum3000 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 3=, q@tD, 8t, 0, 10<EE

In[5]:= PlotBEvaluate@dampedpendulum3000D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-p, p<,Ticks Ø :Automatic, :-p, -

1

2 p, 0,

1

2 p, p>>,

AxesLabel Ø 8Time, Angle<F

In[6]:= g1 = ParametricPlot@Evaluate@8dampedpendulum3000, D@dampedpendulum3000, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, Automatic<D

In the following series of figures we explore the effect of giving the damped pendulum increased amounts of initial energy (increasingly higher initial velocities):

In[7]:= dampedpendulum4000 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 4=, q@tD, 8t, 0, 10<EE

Page 83: Ma Thematic A Manual

In[8]:= PlotBEvaluate@dampedpendulum4000D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-p, p<,Ticks Ø :Automatic, :-p, -

1

2 p, 0,

1

2 p, p>>,

AxesLabel Ø 8Time, Angle<F

In[9]:= g2 = ParametricPlot@Evaluate@8dampedpendulum4000, D@dampedpendulum4000, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

In[10]:= dampedpendulum5000 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 5=, q@tD, 8t, 0, 10<EE

In[11]:= PlotBEvaluate@dampedpendulum5000D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-p, p<,Ticks Ø :Automatic, :-p, -

1

2 p, 0,

1

2 p, p>>,

AxesLabel Ø 8Time, Angle<F

In[12]:= g3 = ParametricPlot@Evaluate@8dampedpendulum5000, D@dampedpendulum5000, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

In[13]:= dampedpendulum6000 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 6=, q@tD, 8t, 0, 10<EE

In[14]:= PlotBEvaluate@dampedpendulum6000D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-p, p<,Ticks Ø :Automatic, :-p, -

1

2 p, 0,

1

2 p, p>>,

AxesLabel Ø 8Time, Angle<F

2 Laboratory 4C.nb

Page 84: Ma Thematic A Manual

In[15]:= g4 = ParametricPlot@Evaluate@8dampedpendulum6000, D@dampedpendulum6000, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

In[16]:= dampedpendulum7000 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 7=, q@tD, 8t, 0, 10<EE

In[17]:= PlotBEvaluate@dampedpendulum7000D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-p, p<,Ticks Ø :Automatic, :-p, -

1

2 p, 0,

1

2 p, p>>,

AxesLabel Ø 8Time, Angle<F

In[18]:= g5 = ParametricPlot@Evaluate@8dampedpendulum7000, D@dampedpendulum7000, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

In[19]:= dampedpendulum8000 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 8=, q@tD, 8t, 0, 10<EE

In[20]:= PlotBEvaluate@dampedpendulum8000D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-p, p<,Ticks Ø :Automatic, :-p, -

1

2 p, 0,

1

2 p, p>>,

AxesLabel Ø 8Time, Angle<F

In[21]:= ParametricPlot@Evaluate@8dampedpendulum8000, D@dampedpendulum8000, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

In[22]:= dampedpendulum8121 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 8.121=, q@tD, 8t, 0, 15<EE

Laboratory 4C.nb 3

Page 85: Ma Thematic A Manual

In[23]:= PlotBEvaluate@dampedpendulum8121D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-p, p<,Ticks Ø :Automatic, :-p, -

1

2 p, 0,

1

2 p, p>>,

AxesLabel Ø 8Time, Angle<F

Note that the pendulum hesitates as it approaches the top of its arc. This shows up in the following figure as a kink (why?).

In[24]:= g6 = ParametricPlot@Evaluate@8dampedpendulum8121, D@dampedpendulum8121, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

In[25]:= dampedpendulum8122 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 8.122=, q@tD, 8t, 0, 15<EE

In[26]:= Plot@Evaluate@dampedpendulum8122D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-0, 3 p<,Ticks Ø 8Automatic, 80, p, 2 p<<,AxesLabel Ø 8Time, Angle<D

The pendulum hesitates, then slips over the top, and comes ultimately to rest at q = 2p.

In[27]:= g7 = ParametricPlot@Evaluate@8dampedpendulum8122, D@dampedpendulum8122, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotStyle Ø RGBColor@0, 0, 1D,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

In[28]:= dampedpendulum9000 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 9=, q@tD, 8t, 0, 10<EE

In[29]:= Plot@Evaluate@dampedpendulum9000D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-0, 3 p<,Ticks Ø 8Automatic, 80, p, 2 p<<,AxesLabel Ø 8Time, Angle<,PlotRange Ø AllD

4 Laboratory 4C.nb

Page 86: Ma Thematic A Manual

In[30]:= g8 = ParametricPlot@Evaluate@8dampedpendulum9000, D@dampedpendulum9000, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotStyle Ø RGBColor@0, 0, 1D,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

In[31]:= dampedpendulum10000 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 10=, q@tD, 8t, 0, 10<EE

In[32]:= Plot@Evaluate@dampedpendulum10000D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-0, 3 p<,Ticks Ø 8Automatic, 80, p, 2 p<<,AxesLabel Ø 8Time, Angle<,PlotRange Ø AllD

In[33]:= g9 = ParametricPlot@Evaluate@8dampedpendulum10000, D@dampedpendulum10000, tD<D, 8t, 0, 10<,PlotRange Ø 88-10, 10<, 8-10, 10<<,PlotStyle Ø RGBColor@0, 0, 1D,PlotPoints Ø 300,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D

Save.

Superimposing all the parametric plots, we obtain

In[34]:= Show@8g1, g2, g3, g4, g5, g6, g7, g8, g9<,Ticks Ø 88-2 p, -p, 0, p, 2 p<, None<,AxesLabel Ø 8q, w<D;

A little quick experimentation puts us in position to bracket the "twice over" point initial velocity space:

In[35]:= twiceover1 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 13.89=, q@tD, 8t, 0, 10<EE

In[36]:= Plot@Evaluate@twiceover1D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-0, 5 p<,Ticks Ø 8Automatic, 80, p, 2 p, 4 p<<,AxesLabel Ø 8Time, Angle<,PlotRange Ø AllD

Laboratory 4C.nb 5

Page 87: Ma Thematic A Manual

In[37]:= g21 = ParametricPlot@Evaluate@8twiceover1, D@twiceover1, tD<D, 8t, 0, 10<,PlotRange Ø 88-p, 15<, 8-15, 15<<,PlotPoints Ø 300,Ticks Ø 88-p, 0, p, 2 p, 3 p, 4 p<, None<,AxesLabel Ø 8q, w<D

In[38]:= twiceover2 = q@tD ê. FirstANDSolveA9q''@tD ã -q'@tD - 32 Sin@q@tDD, q@0D ã 0, q'@0D ã 13.90=, q@tD, 8t, 0, 10<EE

In[39]:= Plot@Evaluate@twiceover2D, 8t, 0, 10<,PlotStyle Ø RGBColor@1, 0, 0D,PlotRange Ø 8-0, 5 p<,Ticks Ø 8Automatic, 80, p, 2 p, 4 p<<,AxesLabel Ø 8Time, Angle<,PlotRange Ø AllD

In[40]:= g22 = ParametricPlot@Evaluate@8twiceover2, D@twiceover2, tD<D, 8t, 0, 10<,PlotRange Ø 88-p, 15<, 8-15, 15<<,PlotStyle Ø RGBColor@0, 0, 1D,PlotPoints Ø 300,Ticks Ø 88-p, 0, p, 2 p, 3 p, 4 p<, None<,AxesLabel Ø 8q, w<D

In preparation for the next superimposition of figures we prepare variants of a couple of previous figures (extended range), which we paint gray:

In[41]:= G1 = ParametricPlot@Evaluate@8dampedpendulum8121, D@dampedpendulum8121, tD<D, 8t, 0, 10<,PlotRange Ø 88-p, 15<, 8-15, 15<<,PlotStyle Ø [email protected],PlotPoints Ø 300,Ticks Ø 88-p, 0, p, 2 p, 3 p, 4 p<, None<,AxesLabel Ø 8q, w<D

In[42]:= G2 = ParametricPlot@Evaluate@8dampedpendulum8122, D@dampedpendulum8122, tD<D, 8t, 0, 10<,PlotRange Ø 88-p, 15<, 8-15, 15<<,PlotStyle Ø [email protected],PlotPoints Ø 300,Ticks Ø 88-p, 0, p, 2 p, 3 p, 4 p<, None<,AxesLabel Ø 8q, w<D

Now the final superpositon:

In[43]:= Show@8G1, G2, g21, g22<, Ticks Ø NoneDThere are yet other ways to represent the results produced by DSolve[ ] and NDSolve[ ]commands.

Save.

6 Laboratory 4C.nb

Page 88: Ma Thematic A Manual

Save.

This is amusing stuff, but raises a philosophical point:

It is gratifying to find that our animations "reproduce the real world," but to the extent that they do so they teach us little more than we would learn by simply looking at the world itself. Previous modes of graphical display~though more "diagramatic," and though they may require some interpretive practice~speak more clearly/informatively to what is going on, teach us how to look at the real world. This much is, in any event clear: When you have solved a differential equation your work is typically only half done; you have yet to devise the best way, in the particular instance, to make your result intelligible. Strings of data~produced maybe this way

In[46]:= TableBdampedpendulum81222 p

ê. t Ø k, 8k, 0, 10, .5<F êê TableForm

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 OscillatorNear the heart of this important subject lies a particular instance

-—2

2 m ∂x,xy@xD +

1

2 m w2 x2 y@xD ã energy y@xD

(— 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@xD2 „x = 1

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

Laboratory 4C.nb 7

Page 89: Ma Thematic A Manual

Our plan is to write

y@xD = f@xD with x = a x

and to assign an "optimal" value to a . Our original Schrodinger equation becomes

In[47]:= -—2

2 m D@f@a xD, x, xD +

1

2 m w2 x2 f@a xD - energy f@a xD

We introduce the x variable

In[48]:= -energy f@x aD +1

2m x2 w2 f@x aD -

—2 a2 f££@x aD2 m

ê. x Ø x ê a

and look for the optimal a :

In[49]:= SolveB m w2

2 a2==

—2 a2

2 m, aF

Adopting the last of those possibilities, we have

In[50]:= -energy f@xD +m x2 w2 f@xD

2 a2-

—2 a2 f££@xD2 m

ê. a -> m w ê —

Finally

In[51]:=2

— w % êê Simplify

leads us to define

K =2 energy

h w

We have at this point recovered the equation reported by Griffiths. Here ends this digression.

Main Discussion~Resumed

The literature supplies many ways to approach

f''@xD - x2 f@xD + K f@xD ã 0

analytically. The resources of Mathematica suggest, however, the following non-standard approach, which has the merit that it does not presume deep knowledge of classical analysis.

We begin by asking what (of an analytical nature) Mathematica has to say in a typical case; we set K = 1, adopt some reasonable-seeming conditions at x = 0 and find…

In[52]:= Clear@x, fD

Mathematica is about to enter a series of complaints. Just hit OK when given the opportunity, not to worry.

8 Laboratory 4C.nb

Page 90: Ma Thematic A Manual

In[53]:= DSolveA9f''@xD - x2 f@xD + 1 f@xD ã 0, f@0D ã 1, f'@0D ã 0=, f@xD, xE

We get a gaussian as expected. We can also proceed numerically:

In[54]:= numericaltest = f@xD ê. FirstANDSolveA9f''@xD - x2 f@xD + 1 f@xD ã 0, f@0D ã 1, f'@0D ã 0=, f@xD, 8x, -10, 10<EE

In[55]:= Plot@Evaluate@numericaltestD, 8x, -4, 4<DWe 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<Ddramatizes the situation, but leaves the question unanswered.

There are a lot of K-values to try. We need to fish in some more systematic way. We elect to use the animation resource to trawl for even normalizable solutions:

In[58]:= AnimateAPlotAEvaluateAf@xD ê. FirstANDSolveA9f''@xD - x2 f@xD + K f@xD ã 0, f@0D ã 1, f'@0D ã 0=, f@xD,8x, -10, 10<EEE, 8x, -6, 6<, PlotRange Ø 8-2, 1.5<E, 8K, 0, 24, 1 ê 2<E

Simple adjustment of the initial data permits us to trawl for odd solutions:

In[59]:= AnimateAPlotAEvaluateAf@xD ê. FirstANDSolveA9f''@xD - x2 f@xD + K f@xD ã 0, f@0D ã 0, f'@0D ã 1=, f@xD,8x, -10, 10<EEE, 8x, -6, 6<, PlotRange Ø 8-2, 1.5<E, 8K, 0, 24, 1 ê 2<E

These movies suggest that we pick up normalizable solutions at the "whip-through" values of K, which in the even case appear to occur at K=1, 5, 9, 13, … and in the odd case to occur at K=3, 7, 11, 15, … We are led by this observation to look again to the complainy output

In[60]:= DSolveA9f''@xD - x2 f@xD + 1 f@xD ã 0, f@0D ã 1, f'@0D ã 0=, f@xD, xE

Note the occurance of C[1] and C[2]; Mathematica has for some reason elected to ignore our initial data statements. The following figures

In[61]:= PlotB‰-

x2

2 x J 1xN

2, 8x, -6, 6<FH*We have set C@1D=1, C@2D=0*L

In[62]:= PlotB‰-

x2

2 xp Erfi@xD

2 x

2, 8x, -6, 6<F

H*We have set C@1D=0, C@2D=1*Llead us~speculatively, experimentally~to abandon the Erfi[x] term.

Laboratory 4C.nb 9

Page 91: Ma Thematic A Manual

lead us~speculatively, experimentally~to abandon the Erfi[x] term.

In[63]:= ? Erfi

Defining

In[64]:= f1@x_D :=‰-

x2

2 x J 1xN

2

we find that this function does satisfy the ODE in question

In[65]:= f1''@xD - x2 f1@xD + 1 f1@xD ã 0 êê Simplify

and that it is normalizable:

In[66]:= ‡-¶

f1@xD2 „x

Enlarging upon this experience, we omit the initial data specifications (seems to be Mathematica's preference)

In[67]:= DSolveA9f''@xD - x2 f@xD + 3 f@xD ã 0=, f@xD, xE

In[68]:= DSolveA9f''@xD - x2 f@xD + 5 f@xD ã 0=, f@xD, xE

In[69]:= DSolveA9f''@xD - x2 f@xD + 7 f@xD ã 0=, f@xD, xE

In[70]:= DSolveA9f''@xD - x2 f@xD + 9 f@xD ã 0=, f@xD, xE

and in each instance set C[1] = 1, C[2] = 0 to obtain

In[71]:= f3@x_D :=‰-

x2

2 x

2

f5@x_D :=1

2 ‰-

x2

2 x 1 -1

2 x2x

f7@x_D :=‰-

x2

2 x I- 32

+ x2M2

f9@x_D :=1

2 ‰-

x2

2 x 1 +3

4 x4-

3

x2x3

This done, we find that

In[75]:= f3''@xD - x2 f3@xD + 3 f3@xD ã 0 êê Simplifyf5''@xD - x2 f5@xD + 5 f5@xD ã 0 êê Simplifyf7''@xD - x2 f7@xD + 7 f7@xD ã 0 êê Simplifyf9''@xD - x2 f9@xD + 9 f9@xD ã 0 êê Simplify

and that

10 Laboratory 4C.nb

Page 92: Ma Thematic A Manual

In[79]:= ‡-¶

f3@xD2 „x

‡-¶

f5@xD2 „x

‡-¶

f7@xD2 „x

‡-¶

f9@xD2 „x

So we have now in hand these normalized oscillator eigenfunctions:

In[83]:= Y1@x_D := f1@xD ì p

2

Y3@x_D := f3@xD ì p

4

Y5@x_D := f5@xD ì p

4

Y7@x_D := f7@xD ì 3 p

8

Y9@x_D := f9@xD ì 3 p

4

That they are normalized is demonstrated by calculations of the form

In[88]:= ‡-¶

Y3@xD2 „x

‡-¶

Y5@xD2 „x

‡-¶

Y7@xD2 „x

while calculations of the form

Laboratory 4C.nb 11

Page 93: Ma Thematic A Manual

In[91]:= ‡-¶

Y3@xD Y5@xD „x

‡-¶

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.

12 Laboratory 4C.nb

Page 94: Ma Thematic A Manual

Physicist's Introduction to MathematicaLaboratory 4Part D

‡ BallisticsConsider the motion of a thrown mass point; immediately

In[2]:= 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

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@qDy@t_, v_, q_, g_D :=

1

2I-g t2 + 2 t v Sin@qDM

In[5]:= undampedflight = TableBParametricPlotB:xBt, 8,k

20p ê 2F, yBt, 8,

k

20p ê 2, 4F>,

8t, 0, 4<, PlotRange Ø 880, 17<, 80, 8.5<<,Ticks Ø None,

AspectRatio Ø AutomaticF, 8k, 0, 19<F;

…and superimpose the frames

In[6]:= Show@undampedflightD…we obtain an image which has been engraved in physics books since early in the 1600s.

Save.

But the following steps culminate in a variant of that same familiar figure which contains an element of sur-prise. First we draw the arcs traced by particles which are launched (all with the same speed) in various directions

In[7]:= arctable = AnimateBParametricPlotB:xBt, 8, k 2 p

30F, yBt, 8, k

2 p

30, 4F>,

8t, 0, 4<, PlotRange Ø 88-35, 35<, 8-70, 10<<,Ticks Ø None,

AspectRatio Ø AutomaticF, 8k, 0, 29<F

Page 95: Ma Thematic A Manual

In[67]:= arctable = TableBParametricPlotB:xBt, 8, k 2 p

30F, yBt, 8, k

2 p

30, 4F>,

8t, 0, 4<, PlotRange Ø 88-35, 35<, 8-70, 10<<,Ticks Ø None,

AspectRatio Ø AutomaticF, 8k, 0, 29<F;

Next we construct a representation of where that population of particles resides at time t = 4:

In[8]:= pointtable = TableBPointB:xB4, 8, k 2 p

30F, yB4, 8, k

2 p

30, 4F>F, 8k, 0, 29<F;

In[9]:= Show@Graphics@[email protected], RGBColor@1, 0, 0D, pointtable<D,PlotRange Ø All,AspectRatio Ø AutomaticD

and finally we superimpose those figures:

In[10]:= Show@arctable, Graphics@[email protected], RGBColor@1, 0, 0D, pointtable<DDThe 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 vectorLWe ask Mathematica to solve

In[11]:= 8X@tD, Y@tD< ê.First@DSolve@8X''@tD ã -b X'@tD, Y''@tD ã -b Y'@tD - g, X@0D ã 0, Y@0D ã 0,

X'@0D ã v Cos@qD, Y'@0D ã v Sin@qD<, 8X@tD, Y@tD<, tDDTo discover what this is telling us we proceed graphically, exactly as before; we define

In[12]:= X@t_, v_, q_, b_D :=‰-b t I-1 + ‰b tM v Cos@qD

b

Y@t_, v_, q_, g_, b_D :=

-1

b2 I‰-b t Ig - ‰b t g + b ‰b t g t + b v Sin@qD - b ‰b t v Sin@qDMM

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:

2 Laboratory 4D.nb

Page 96: Ma Thematic A Manual

In[14]:= dampedflight =

TableBParametricPlotB:XBt, 8,k

20p ê 2, 3

10F, YBt, 8,

k

20p ê 2, 4,

3

10F>,

8t, 0, 4<, PlotRange Ø 880, 17<, 80, 8.5<<,Ticks Ø None,AspectRatio Ø Automatic,

PlotStyle Ø RGBColor@0, 0, 1DF, 8k, 0, 19<F;

In[15]:= Show@dampedflightD

In[16]:= Show@undampedflight, dampedflightD

‡ Planetary MotionSo well known is this problem that, without physical preamble, we proceed

In[17]:= Clear@x, y, a, bD

In[18]:= DSolveB:x''@tD ã -x@tD

Ix@tD2 + y@tD2M3

2

, y''@tD ã -y@tD

Ix@tD2 + y@tD2M3

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):

In[19]:= orbit1 = NDSolveB:x''@tD ã -x@tD

Ix@tD2 + y@tD2M3

2

, y''@tD ã -y@tD

Ix@tD2 + y@tD2M3

2

,

x@0D ã 1, y@0D ã 0, x'@0D ã 0, y'@0D ã .5>, 8x@tD, y@tD<, 8t, 0, 3<F

In[20]:= firstorbit = ParametricPlot@Evaluate@8x@tD, y@tD< ê. orbit1D, 8t, 0, 2<,PlotRange Ø All,AspectRatio Ø Automatic,PlotStyle Ø RGBColor@0, 0, 1DD

In[21]:= orbit2 = NDSolveB:x''@tD ã -x@tD

Ix@tD2 + y@tD2M3

2

, y''@tD ã -y@tD

Ix@tD2 + y@tD2M3

2

,

x@0D ã 1, y@0D ã 0, x'@0D ã 0, y'@0D ã .6>, 8x@tD, y@tD<, 8t, 0, 3<F

In[22]:= secondorbit = ParametricPlot@Evaluate@8x@tD, y@tD< ê. orbit2D, 8t, 0, 2<,PlotRange Ø All,AspectRatio Ø Automatic,PlotStyle Ø RGBColor@1, 0, 0DD

Laboratory 4D.nb 3

Page 97: Ma Thematic A Manual

In[23]:= orbit3 = NDSolveB:x''@tD ã -x@tD

Ix@tD2 + y@tD2M3

2

, y''@tD ã -y@tD

Ix@tD2 + y@tD2M3

2

,

x@0D ã 1, y@0D ã 0, x'@0D ã 0, y'@0D ã .4>, 8x@tD, y@tD<, 8t, 0, 3<F

In[24]:= thirdorbit = ParametricPlot@Evaluate@8x@tD, y@tD< ê. orbit3D, 8t, 0, 2<,PlotRange Ø All,AspectRatio Ø AutomaticD

In[25]:= Show@firstorbit, secondorbit, thirdorbitD;One could write a book about this system (Newton did, NASA has, and so have a million others), but I will make only one further observation~illustrative of how easy it is to go exploring with the bright assistance of Mathematica. Let us modify~slightly~the force law:

In[26]:= superperturbedorbit =

NDSolveB:x''@tD ã -x@tD

Ix@tD2 + [email protected], y''@tD ã -

y@tDIx@tD2 + [email protected]

,

x@0D ã 1, y@0D ã 0, x'@0D ã 0, y'@0D ã .4>, 8x@tD, y@tD<, 8t, 0, 10<F

In[27]:= ParametricPlot@Evaluate@8x@tD, y@tD< ê. superperturbedorbitD, 8t, 0, 9<,PlotRange Ø All,AspectRatio Ø AutomaticD

Compare that non-reentrant orbit with the following one:

In[28]:= subperturbedorbit =

NDSolveB:x''@tD ã -x@tD

Ix@tD2 + [email protected], y''@tD ã -

y@tDIx@tD2 + [email protected]

,

x@0D ã 1, y@0D ã 0, x'@0D ã 0, y'@0D ã .4>, 8x@tD, y@tD<, 8t, 0, 10<F

In[29]:= ParametricPlot@Evaluate@8x@tD, y@tD< ê. subperturbedorbitD, 8t, 0, 9<,PlotRange Ø All,AspectRatio Ø AutomaticD

The precession is prograde in the former case, retrograde in the latter. The following experiment

In[30]:= barelysuperperturbedorbit =

NDSolveB:x''@tD ã -x@tD

Ix@tD2 + [email protected], y''@tD ã -

y@tDIx@tD2 + [email protected]

,

x@0D ã 1, y@0D ã 0, x'@0D ã 0, y'@0D ã .4>, 8x@tD, y@tD<, 8t, 0, 15<F

In[31]:= ParametricPlot@Evaluate@8x@tD, y@tD< ê. barelysuperperturbedorbitD, 8t, 0, 15<,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.

4 Laboratory 4D.nb

Page 98: Ma Thematic A Manual

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 ConditionsWe are in the habit of specifying orbits by stipulating initial conditions, but in advanced mechanics one devel-ops (in connection with the way certain "variational principles" are phrased) an interest in the orbits which conform to stipulated endpoint conditions; indeed, a pitcher has something resembling endpoint conditions in mind when he pitches the ball. Here I want only to point out that Mathematica takes endpoint conditions in easy stride.

Look, by way of illustration, to the familiar harmonic oscillator:

In[32]:= DSolveA9x''@tD ã -w2 x@tD, x@0D ã a, x@TD ã b=, x@tD, tE

We resort once again to graphical techniques to display what we have accomplished:

In[33]:= x@t_, T_, a_, b_, w_D := a Cos@t wD + H-a Cot@T wD + b Csc@T wDL Sin@t wD

In[34]:= endpoints = List@Point@80, .5<D, [email protected], -1<DD

In[35]:= connectingorbits = PlotB:

xBt, 7

4, .5, -1, 2 pF,

xBt, 7

4, .5, -1, 2 p + .1F,

xBt, 7

4, .5, -1, 2 p + .2F,

xBt, 7

4, .5, -1, 2 p + .3F,

xBt, 7

4, .5, -1, 2 p + .4F>, :t, 0,

7

4>, PlotRange Ø 88-.2, 2<, 8-2, 2<<,

Ticks Ø 881.75<, 8.5<<, AxesLabel Ø 8time, displacement<F;

In[36]:= Show@connectingorbits,Graphics@[email protected], RGBColor@1, 0, 0D, endpoints<DD

Save.

Laboratory 4D.nb 5

Page 99: Ma Thematic A Manual

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

Laboratory 5Part A

Partial Differential Equations

When you ask Mathematica to solve an ordinary DE~say

I1 - x2M y''@xD - x y'@xD + n2 y@xD ã 0

or

x''@tD + b x'@tD + w2 x@tD ã DiracDelta@tD~it has powerful resources to draw upon (the "Kovacic algorithm," "Bocharov techniques," etc.…with alto-gether use about 300 pages of Mathematica code and 200 pages of C code), and often has immediate things to say:

In[2]:= DSolveAI1 - x2M y''@xD - x y'@xD + n2 y@xD ã 0, y@xD, xE

In[3]:= DSolveAx''@tD + b x'@tD + w2 x@tD ã DiracDelta@tD, x@tD, tE

And when those techniques fail one can proceed numerically, with NDSolve.

Partial differential equations (PDEs) are, however, a different story. Though

In[4]:= ? DSolve

does speak of PDEs, and Mathematica is by no means powerless in this area, it often responds unhelpfully. Look, for example, to the one-dimensional heat equation

∂t u@x, tD ã a ∂x,xu@x, tDconcerning which we are told that

In[5]:= DSolve@∂tu@x, tD ã a ∂x,xu@x, tD, u@x, tD, 8x, t<DBut if we proceed as suggested

Page 100: Ma Thematic A Manual

But if we proceed as suggested

Doubtless there is much about this subject I myself have yet to learn, but it has been my experience that if I~confronted with a PDE~have a plan of attack, then Mathematica will assist me in management of the details. But Mathematica will not usually suggest a plan of attack; for those I must read books. PDE's are not nearly so "cut and dried" as ODEs. Let us look to an illustrative instance:

‡ Waves on a StringThe one dimensional wave equation reads

c2 ∂x,xu@x, tD - ∂t,tu@x, tD ã 0

Proceeding

In[8]:= DSolveAc2 ∂x,xu@x, tD - ∂t,tu@x, tD ã 0, u@x, tD, 8x, t<E

Mathematica informs us that we obtain a solution when we write

In[9]:= u@x, tD := FBt +x

cF + GBt -

x

cF H*Any F@D, any G@D*L

We learned this already from class work, but check it out:

In[10]:= c2 ∂x,xu@x, tD - ∂t,tu@x, tD ã 0

In[11]:= Simplify@%D

In[12]:= Clear@u, f, gDSuppose we sought a solution with the property that

u@x, 0D = f@xD H*any f@D*LLimit@∂t u@x, tD, t Ø 0D = g@xD H*any g@D*L

The command

In[13]:= DSolveA9c2 ∂x,xu@x, tD - ∂t,tu@x, tD ã 0,

u@x, 0D == f@xD,Limit@∂t u@x, tD, t Ø 0D == g@xD=, u@x, tD, 8x, t<E

got us nowhere. Yet we learn from books that an elegant solution of that initial value problem was known already (by about 1750) to d'Alembert:

In[14]:= u@x, tD =1

2 Hf@x + c tD + f@x - c tDL +

1

2 c ‡

x-c t

x+c t

g@xD „x

And Mathematica, once pointed in the right direction, is quick to agree with d'Alembert:

In[15]:= c2 ∂x,xu@x, tD - ∂t,tu@x, tD ã 0

In[16]:= Simplify@%D

2 Laboratory 5A.nb

Page 101: Ma Thematic A Manual

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

In[19]:= u@x, tD := SinBt -x

cF

In[20]:= c2 ∂x,xu@x, tD - ∂t,tu@x, tD ã 0

In[21]:= j@x, tD := u@x, tD ê. c Ø 1

In[22]:= j@x, tDIf we wanted to display that result on the printed page we might proceed

In[23]:= Plot3D@Sin@t - xD, 8x, -2 p, 2 p<, 8t, 0, 6<, PlotPoints Ø 30,AxesLabel Ø 8FontForm@"position", 8"Helvetica-Bold", 12<D,FontForm@"time", 8"Helvetica-Bold", 12<D,FontForm@"amplitude", 8"Helvetica-Bold", 12<D<,

Ticks Ø 88-2 p, -p, 0, p, 2 p<, Automatic, None<D;but if we planned to speak about it in a modern lecture hall we would probably find it more effective to make a movie:

In[24]:= TableBPlotBSinBk 6

20- xF, 8x, -2 p, 2 p<F;, 8k, 0, 20<F;

Watch the movie, then delete the filmstrip and Save.

Second Example

In[25]:= u@x, tD := SinBt -x

cF +

1

3 CosB3 t +

x

cF

In[26]:= c2 ∂x,xu@x, tD - ∂t,tu@x, tD ã 0

In[27]:= Simplify@%D

In[28]:= j@x, tD := u@x, tD ê. c Ø 1

In[29]:= j@x, tDThe static 3D figure is now almost too complicated to be informative:

Laboratory 5A.nb 3

Page 102: Ma Thematic A Manual

In[30]:= Plot3D@Sin@t - xD, 8x, -2 p, 2 p<, 8t, 0, 6<, PlotPoints Ø 30,AxesLabel Ø 8"position", "time", "amplitude"<,Ticks Ø 88-2 p, -p, 0, p, 2 p<, Automatic, None<D

Animation clarifies the meaning of the figure:

In[31]:= AnimateBPlotB13CosB3 k

6

40+ x F + SinBk

6

40- xF,

8x, -2 p, 2 p<, PlotRange Ø 8-2, 2<F, 8k, 0, 40<F;

NOTICE that in both of the preceding figures I have increased the resolution (number of PlotPoints, number of frames) to accommo-date the increased density of detail.

Third Example: d'Alembert's Solution

d'Alembert speaks of the wave form that evolves from prescribed initial data (a "thrown wave," if you will…the term borrowed from what we prescribe when we throw a rock). Our first example

In[32]:= u@x, tD := Sin@t - xDentails

In[33]:= f@xD := Limit@u@x, tD, t Ø 0Dg@xD := Limit@∂t u@x, tD, t Ø 0D

In[35]:= f@xDg@xD

d'Alembert would use that data to construct

In[37]:=1

2 H-Sin@x + tD - Sin@x - tDL +

1

2 ‡

x- t

x+ t

Cos@xD „x

In[38]:= Simplify@%Dwhich does indeed reproduce our known (and previously plotted) starting point. Look to this more interesting case:

Gaussian Initial Profile, String Initially at Rest

In[39]:= f@xD := ‰-x2ë4

g@xD := 0

d'Alembert asserts that

In[41]:= u@x, tD :=1

2 K‰-Hx+tL2í4 + ‰-Hx-tL2í4O

In[42]:= ∂x,xu@x, tD - ∂t,tu@x, tD ã 0

In[43]:= Simplify@%D

4 Laboratory 5A.nb

Page 103: Ma Thematic A Manual

In[44]:= Plot3DB12

K‰-Hx+tL2í4 + ‰-Hx-tL2í4O, 8x, -2 p, 2 p<, 8t, 0, 6<, PlotPoints Ø 50,

AxesLabel Ø 8"position", "time", "amplitude"<,Ticks Ø 88-2 p, -p, 0, p, 2 p<, Automatic, None<F

In[45]:= AnimateBPlotB12

‰-Jx+k

6

30N2 ì 4

+ ‰-Jx-k

6

30N2 ì 4

, 8x, -2 p, 2 p<,

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<Dvanishes.

‡ Separation with Respect to the Time Variable

We assume j[x,y,t] to have the factored design

j@x, y, tD = u@x, yD * f@tDThe left side of the wave equation then becomes

In[47]:= c2 HD@u@x, yD f@tD, 8x, 2<D + D@u@x, yD f@tD, 8y, 2<DL - D@u@x, yD f@tD, 8t, 2<DDivision by u[x,y]f[t]gives

In[48]:=-u@x, yD f££@tDu@x, yD f@tD +

c2 f@tD uH0,2L@x, yDu@x, yD f@tD +

c2 f@tD uH2,0L@x, yDu@x, yD f@tD

which can vanish if and only if these two statements are separately true:

-f££@tDf@tD = constant

Laboratory 5A.nb 5

Page 104: Ma Thematic A Manual

uH0,2L@x, yDu@x, yD +

uH2,0L@x, yDu@x, yD +

constant

c2= 0

We are interested in the oscillatory solutions of the first equation (which is to say: not interested in exponential explosion/death), so we enforce constant > 0 by writing

constant = w2

Our original PDE has thus "separated" into an ODE

f££@tD + w2 f@tD = 0

and a PDE involving only 2 (instead of the original 3) independent variables:

uH0,2L@x, yD + uH2,0L@x, yD +w2

c2 u@x, yD = 0

The former gives

In[49]:= DSolveAf££@tD + w2 f@tD ã 0, f@tD, tE

while the latter can be written

uH0,2L@x, yD + uH2,0L@x, yD + k2 u@x, yD = 0

(this is the 2-dimensional Helmholtz equation) with

k2 =w2

c2

which we will find it most convenient to express

w@k_D := c k

‡ Polar Separation of the Helmholtz EquationThe objective now is to resolve Helmholtz' PDE into a pair of ODEs, and to do so in a way that respects the symmetry of our circular drumhead~that so we can express the physical circumstance that the boundary of the drumhead has been "clamped." To that end, we introduce polar coordinates in the usual way

x = r Cos@qDy = r Sin@qD

and write

u@x, yD = F@r@x, yD, q@x, yDDwith

In[50]:= r@x_, y_D := x2 + y2

q@x_, y_D := ArcTan@x, yD

In[52]:= ? ArcTan

The Laplacian of u[x,y] is by these adjustments brought to the form

6 Laboratory 5A.nb

Page 105: Ma Thematic A Manual

The Laplacian of u[x,y] is by these adjustments brought to the form

In[53]:= D@F@r@x, yD, q@x, yDD, 8x, 2<D +

D@F@r@x, yD, q@x, yDD, 8y, 2<D

In[54]:= Simplify@%D

In[55]:= % ê. 9x2 + y2 Ø r2, ArcTan@x, yD Ø q=

In[56]:= Simplify@%, r > 0D

Short Digression

The command

In[57]:= SimplifyB r2 F

does nothing because Mathematica considers the result to depend on whether r is positive or negative, and does not know which we intend. So we tell it:

In[58]:= SimplifyB r2 , r > 0F

In the alternative case we would have obtained

In[59]:= SimplifyB r2 , r < 0F

Now we return to the main discussion.

We next make again the characteristic "separation assumption" that

F@r, qD = R@rD * A@qDOur former Helmholz equation

uH0,2L@x, yD + uH2,0L@x, yD + k2 u@x, yD = 0

is brought thus to the form of a requirement that

In[60]:= H R@rD A''@qD + r HR'@rD A@qD + r R''@rD A@qDLL + k2 r2 R@rD A@qDvanish. Division by R[r]A[q] gives

In[61]:=R@rD A££@qDR@rD A@qD +

r A@qD HR£@rD + r R££@rDLR@rD A@qD +

k2 r2 R@rD A@qDR@rD A@qD

~the vanishing of which requires that

A££@qDA@qD = constant

Laboratory 5A.nb 7

Page 106: Ma Thematic A Manual

k2 r2 +r HR£@rD + r R££@rDL

R@rD + constant = 0

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@qDThis requires that we look only to the periodic solutions of the ODE

A''@qD - constant * A@qD = 0

So we set

constant = -m2

and our final separated equations read

f''@tD + c2 k2 f@tD = 0

A''@qD + m2 A@qD = 0

r HR£@rD + r R££@rDL + Ik2 r2 - m2M R@rD = 0

We have made two separations, and our final equations contain therefore two separation constants: k and m .

This complete my illustrative discussion of how one achieves separation (reduction of a PDE to a set of constant-coupled ODEs), but there is more to be said~both mathematically and physically: From

In[62]:= DSolveAA''@qD + m2 A@qD ã 0, A@qD, qE

we learn that m must be an integer: m=0,1,2,… Next we look to

In[63]:= DSolveAr2 R''@rD + r R'@rD + Ik2 r2 - 12M R@rD ã 0, R@rD, rE

and find that we have been led to Bessel functions:

In[64]:= ? BesselJ

In[65]:= ? BesselY

On the following graphical evidence

In[66]:= Plot@BesselJ@0, xD, 8x, 0, 10<D

In[67]:= Plot@BesselJ@1, xD, 8x, 0, 10<D

In[68]:= Plot@BesselY@1, xD, 8x, 0, 10<Dwe 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

In[69]:= j1@r_, q_, t_, k_, m_D := BesselJ@m, k rD Cos@m qD Cos@c k tDj2@r_, q_, t_, k_, m_D := BesselJ@m, k rD Sin@m qD Cos@c k tDj3@r_, q_, t_, k_, m_D := BesselJ@m, k rD Cos@m qD Sin@c k tDj4@r_, q_, t_, k_, m_D := BesselJ@m, k rD Sin@m qD Sin@c k tD

But we require~clamped boundary condition~that

8 Laboratory 5A.nb

Page 107: Ma Thematic A Manual

But we require~clamped boundary condition~that

j@a, q, tD = 0 H* all q, all t; a is radius of drum *LWe 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

In[73]:= 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<,8"Third root of J0", FindRoot@BesselJ@0, xD ã 0, 8x, 9<D<D êê TableForm

In[74]:= List@8"First root of J1", FindRoot@BesselJ@1, xD ã 0, 8x, 4<D<,8"Second root of J1", FindRoot@BesselJ@1, xD ã 0, 8x, 7<D<,8"Third root of J1", FindRoot@BesselJ@1, xD ã 0, 8x, 10<D<D êê TableForm

This means that the physically admissible values of the separation constant k are those given in the following table (actually in its completion: I give only the leading fragment):

In[75]:= List@88k0,1, 2.40483 ê a<, 8k0,2, 5.52008 ê a<,8k0,3, 8.65373 ê a<<,

88k1,1, 3.83171 ê a<, 8k1,2, 7.01559 ê a<,8k1,3, 10.1735 ê a<<D êê TableForm

and that the corresponding frequencies are given by

wi,j = c ki,j

The "fundamental" (lowest frequency) is the (0,1)-mode, and the next highest is seen to be not the (0,2)-mode but the (1,1)-mode.

Let us, for graphical purposes, set a = c = 1 and define

In[76]:= fundamental@x_, y_, t_D :=

BesselJB0, 2.40483 x2 + y2 F Cos@0 ArcTan@y, xDD Cos@ 2.40483 tDfirstharmonic@x_, y_, t_D :=

BesselJB1, 3.83171 x2 + y2 F Cos@1 ArcTan@y, xDD Cos@ 3.83171 tDhigherharmonic@x_, y_, t_D :=

BesselJB5, 8.77148 x2 + y2 F Cos@5 ArcTan@y, xDD Cos@ 8.77148 tD

REMARK: Plot3D does not know about polar coordinates, works only in Cartesian coordinates…which is why we have described the preceding modes as functions of x & y rather than r & theta.

Save.

Laboratory 5A.nb 9

Page 108: Ma Thematic A Manual

In[79]:= AnimateBPlot3DBEvaluateBfundamentalBx, y,1

2.40483 2 p

10 kFF, 8x, -1, 1<,

8y, -1, 1<, PlotRange Ø 8-1, 1<, PlotPoints Ø 25F, 8k, 0, 9<F

REMARK: I do not know of any way to "trim the corner scrap," i.e., to omit the points where x2 + y 2 > 1. Short of that, one might usefully superimpose an image of the circular drum rim.

In[80]:= AnimateBPlot3DBEvaluateBfirstharmonicBx, y,1

3.83171 2 p

10 kFF,

8x, -1, 1<, 8y, -1, 1<, PlotRange Ø 8-1, 1<, PlotPoints Ø 25,Boxed Ø False,

Axes Ø FalseF, 8k, 0, 9<F

In[81]:= AnimateBPlot3DBEvaluateBhigherharmonicBx, y,1

8.77148 2 p

10 kFF,

8x, -1, 1<, 8y, -1, 1<, PlotRange Ø 8-1, 1<, PlotPoints Ø 35,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

In[82]:= Table@BesselJ@n, 0D, 8n, 0, 10<D êê N

Evidently JnH0L = 0 unless n = 0. Physically: if you strike the drumhead at dead center you excite only the fundamental, and you excite higher and higher harmonics as you strike closer and closer to the rim…all of which is entirely consistent with your direct experience.

‡ Modes of an Annular Drum

Such a drum possesses both an outer rim and an inner rim, which we take to be concentric circles of radii a and b , with a<b . The vibrational physics is unchanged from the physics just discussed; what changes are the boundary conditions. Bessel functions of the 2nd kind come now into play; separation leads us to

j1@r_, q_, t_, k_, b_, m_D :=

HCos@bD BesselJ@m, k rD + Sin@bD BesselY@m, k rDL * Cos@m qD * Cos@c k tDand 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 aDand

Cos@bD BesselJ@m, k bD + Sin@bD BesselY@m, k bDboth 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

10 Laboratory 5A.nb

Page 109: Ma Thematic A Manual

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 Ø [email protected], RGBColor@0, 0, 1D<,Frame Ø False,Axes -> True,Ticks Ø 88-p, -p ê 2, 0, p ê 2, p<, Automatic<,AxesLabel Ø 8"mixing angle", "k"<D

Do the same for

rimfunction@b, k, 1.0D = 0 :

which will take a minute, be patient:

In[85]:= outerrim = ContourPlot@rimfunction@b, k, 1D, 8b, -p, p<, 8k, .001, 10<,PlotPoints Ø 100,ContourShading Ø False,Contours Ø 80<,ContourStyle Ø [email protected], RGBColor@1, 0, 0D<,Frame Ø False,Axes -> True,Ticks Ø 88-p, -p ê 2, 0, p ê 2, p<, Automatic<,AxesLabel Ø 8"mixing angle", "k"<D

Intersection points in the following figure identify the points where both conditions are satisfied:

In[86]:= Show@innerrim, outerrimDThe k - coordinates of the intersection points (this figure, extended to higher k-values, together with similar figures for m=1,2,3,…) give the natural frequencies of the annular drum. It would be interesting to pursue the finer details…but the effort would take us too far away from our main topic.

‡ Summary Remarks Concerning the Separation MethodThe following remarks are of general significance, but will be phrased as they relate to our experience with the drum problem:

• Separation proceeded from a strong factorization assumption

u@r, q, tD = R@rD * A@qD * f@tDand 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.

Laboratory 5A.nb 11

Page 110: Ma Thematic A Manual

• Spectral discreteness arose not from the PDE itself (which speaks in the language of smooth variation) but from the associated boundary conditions. It is from this same circumstance that quantum mechanics acquires the quantal discreteness to which its name refers.

• Mathematica made duck soup of the computational/graphic details, but we ourselves were responsible for the controlling ideas~responsible, in particular, for the decision to work in polar coordinates.

• The decision to work in polar coordinates served us in two distinct ways: (1) it permitted separation of the PDE, and (2) it permitted natural description of the boundary conditions. The theory in hand could be adapted to a theory of wedge-shaped drumheads (more generally: any drumheads bounded by arcs of constant r and arcs of constant q), but it has nothing to say about (say) elliptical drums, or annular drumheads with off-center holes.

REMARK: All strings have the same shape, and support therefore similar sets of harmonics. But drums (2-dimensional systems) have different shapes, and therefore support distinct sets of harmonics. It becomes plausible to speculate that one can "hear the shape of a drum."

• Our ability to adapt the separation of variables method to other physical problems is limited by our command of separating coordinate systems, and we can expect in all events to be able to deal only with systems in which the boundaries conform to the geometry of whatever coordinate system we have selected. (In other~more general cases~we would have to fall back on numerical methods which are a vast subject in themselves.)

The latter circumstance has~more than any other~inspired development of a great number of wonder-ful coordinate systems, about which Mathematica knows a great deal:

Save, close then reopen Mathematica, and proceed to Part B.

12 Laboratory 5A.nb

Page 111: Ma Thematic A Manual

Physicist's Introduction to MathematicaLaboratory 5Part B

Curvilinear Coordinate Systems

Look up "curvilinear coordinates" in Help > Documentation Center… and you will be informed that Mathemat-ica's knowledge of this subject resides in a Standard Package:

In[2]:= Needs@"VectorAnalysis`"DWhen we open what Help has to say about that package we see a list and descriptions of fourteen 3-dimen-sional coordinate systems (many of which you have never heard of), and are introduced to these commands:

In[3]:= ? CoordinateSystem

In[4]:= ? Coordinates

If we try those

In[5]:= 8CoordinateSystem, Coordinates@D<we discover that Mathematica~until instructed otherwise~assumes us to be working in Cartesian coordinates, and to be calling them x, y, z (or perhaps X, Y, Z). The names it presumes we will give to (say) spherical coordi-nates are

In[6]:= Coordinates@SphericalDand the command

In[7]:= ? CoordinatesToCartesian

tells us how Mathematica assumes the spherical coordinate system to have been constructed:

In[8]:= CoordinatesToCartesian@8r, q, f<, SphericalDThis means that Mathematica has defined

In[9]:= x@r_, q_, f_D := r Sin@qD Cos@fDy@r_, q_, f_D := r Sin@qD Sin@fDz@r_, q_, f_D := r Cos@qD

and so interprets q to be not latitude but "colatitude": q is 0 at the north pole, p at the south pole (not at the equator, as is geographers and some physicists/mathematicians assume). This is, in particular, the spherical system employed by Griffiths in his Introduction to Electrodynamics (see the endpapers). To clarify the situa-tion, we have the command

Page 112: Ma Thematic A Manual

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@SphericalDTo discover how Mathematica would describe r, q, f in terms of x, y, z we command

In[14]:= CoordinatesFromCartesian@8x, y, z<, SphericalDIt is often useful to have before us a picture of the curvilinear coordinate system under consideration. To obtain such images, we proceed

In[15]:= constantradius =

ParametricPlot3DB8x@1, q, fD, y@1, q, fD, z@1, q, fD<, :q,p

8, p>, :f, 0,

3

2 p>F

In[16]:= constanttheta = ParametricPlot3DB

8x@r, p ê 4, fD, y@r, p ê 4, fD, z@r, p ê 4, fD<, :r, 0,3

2>, :f, 0,

3

2 p>F

In[17]:= constantlongitude =

ParametricPlot3DB:xBr, q,p

8F, yBr, q,

p

8F, zBr, q,

p

8F>, :r, 0,

3

2>, :q,

p

8, p>F

In[18]:= Show@constantradius, constanttheta, constantlongitudeDNotice that I have opened the figure up (restricted the range of the variables) to show better how the surfaces of constant r, constant q and constant f interrelate.

Save.

The preceding figures contain no surprises, but their analogs in more exotic cases can be expected to teach us useful things we did not know. Look, for example, to the following case:

In[19]:= Coordinates@ParaboloidalD

In[20]:= CoordinateRanges@ParaboloidalD

In[21]:= CoordinatesToCartesian@8v, u, f<, ParaboloidalD

In[22]:= CoordinatesFromCartesian@8x, y, z<, ParaboloidalD

In[23]:= Clear@x, y, z, u, v, fD

In[24]:= x@v_, u_, f_D := u v Cos@fDy@v_, u_, f_D := u v Sin@fDz@v_, u_, f_D :=

1

2I-u2 + v2M

2 Laboratory 5B.nb

Page 113: Ma Thematic A Manual

In[27]:= constantv =

ParametricPlot3DB8x@1, u, fD, y@1, u, fD, z@1, u, fD<, 8u, 0, 3<, :f, 0,3

2 p>F

After the following command you will get a message; hit OK and you'll be OK.

In[28]:= constantu =

ParametricPlot3DB8x@v, 1, fD, y@v, 1, fD, z@v, 1, fD<, 8v, 0, 3<, :f, 0,3

2 p>F

In[29]:= constantphi =

ParametricPlot3DB:xBv, u,p

8F, yBv, u,

p

8F, zBv, u,

p

8F>, 8v, 0, 3<, 8u, 0, 3<F

In[30]:= Show@constantv, constantu, constantphiD

Drag the final figure to size, to improve clarity.

Save.

Many of the coordinate systems known to Mathematica are really parameterized families of similarly con-structed coordinate systems, and acquire specific meaning only when numerical values have been assigned to the parameters in question. Thus

In[31]:= ? ConfocalEllipsoidal

In[32]:= CoordinatesToCartesian@8l, m, n<, ConfocalEllipsoidal@l, m, n, a, b, cDD

In[33]:= ? Toroidal

In[34]:= CoordinatesToCartesian@8u, v, f<, Toroidal@u, v, f, aDDAfter 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@ConfocalEllipsoidalDare helpful in this general regard.

It is clear from the figures already in our possession that the coordinate surfaces intersect orthogonally. This characteristic property of "named" coordinate systems is responsible for much of their interest and utility.

The theory of multivariable integration supplies

dxdydz = Jacobian * dudvdw

where the Jacobian is the determinant of the matrix of first partials. Look again, by way of illustration, to the spherical coordinate system

Laboratory 5B.nb 3

Page 114: Ma Thematic A Manual

where the Jacobian is the determinant of the matrix of first partials. Look again, by way of illustration, to the spherical coordinate system

In[39]:= Clear@x, y, z, r, q, fD

In[40]:= x@r_, q_, f_D := r Sin@qD Cos@fDy@r_, q_, f_D := r Sin@qD Sin@fDz@r_, q_, f_D := r Cos@qD

If we were working by hand on paper, we would proceed along these lines:

In[43]:= matrixoffirstpartials =D@x@r, q, fD, rD D@x@r, q, fD, qD D@x@r, q, fD, fDD@y@r, q, fD, rD D@y@r, q, fD, qD D@y@r, q, fD, fDD@z@r, q, fD, rD D@z@r, q, fD, qD D@z@r, q, fD, fD

In[44]:= Det@%D êê Simplify

Mathematica has already released us from many minutes of tedious work. But Mathematica is smart enough to do such work automatically:

In[45]:= ? JacobianMatrix

In[46]:= JacobianMatrix@Spherical@r, q, fDD

In[47]:= ? JacobianDeterminant

In[48]:= JacobianDeterminant@Spherical@r, q, fDDLook at what Help has to say about the Calculus`VectorAnalysis` package and you will find that it provides quite a number of similarly powerful/useful resources.

Mathematica has a built-in ability to compute the gradiant of a scalar field

In[49]:= Grad@f@x, y, zD, Cartesian@x, y, zDDthe divergence and curl of a vector field

In[50]:= Div@8u@x, y, zD, v@x, y, zD, w@x, y, zD<, Cartesian@x, y, zDD

In[51]:= Curl@8u@x, y, zD, v@x, y, zD, w@x, y, zD<, Cartesian@x, y, zDDthe Laplacian of a scalar field

In[52]:= Laplacian@f@x, y, zD, Cartesian@x, y, zDDand 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, zDDIn 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)

4 Laboratory 5B.nb

Page 115: Ma Thematic A Manual

The beauty of the situation is that Mathematica can do the same thing~with equal ease~in any of the coordi-nate systems of which it has knowledge. Suppose we were working in spherical coordinates; then we would have (for example)

In[54]:= Grad@f@r, q, fD, Spherical@r, q, fDD~precisely as reported by Griffiths on the front endpaper of his Electrodynamics. For

In[55]:= Div@8u@r, q, fD, v@r, q, fD, w@r, q, fD<, Spherical@r, q, fDD

In[56]:= Simplify@%DMathematica 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[57]:= % ==1

r2 ∂r Ir2 u@r, q, fDM +

1

r Sin@qD ∂qH v@r, q, fD Sin@qDL +

1

r Sin@qD ∂f w@r, q, fD H* That's Griffiths' result on the right *L

In[58]:= Simplify@%DThe 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

In[60]:= % ==1

r2 ∂r Ir2 ∂r f@r, q, fDM +

1

r2 Sin@qD ∂qHSin@qD ∂q f@r, q, fDL +

1

r2 Sin@qD2∂f,ff@r, q, fD êê

Simplify H* That's again Griffiths on the right*LLet us see how this result feeds into the separation strategy. First we assume

f@r, q, fD = R@rD * Y@q, fDand compute

In[61]:=Laplacian@R@rD Y@q, fD, Spherical@r, q, fDD

R@rD Y@q, fD êê Simplify

Multiplication by r2 gives

In[62]:=r Y@q, fD H2 R£@rD + r R££@rDL

R@rD Y@q, fD +R@rD Csc@qD2 YH0,2L@q, fD

R@rD Y@q, fD +

R@rD Cot@qD YH1,0L@q, fDR@rD Y@q, fD +

R@rD YH2,0L@q, fDR@rD Y@q, fD

in which r has been separated from the angular variables. Next we assume

Y@q, fD = P@qD * Q@fDand find

Laboratory 5B.nb 5

Page 116: Ma Thematic A Manual

In[63]:=Csc@qD2 ∂f,fHP@qD Q@fDL

P@qD Q@fD +Cot@qD ∂q HP@qD Q@fDL

P@qD Q@fD +∂q,qHP@qD Q@fDL

P@qD Q@fD

Division by Csc@qD2 gives

In[64]:=Cot@qD P£@qDCsc@qD2 P@qD

+P££@qD

Csc@qD2 P@qD+Csc@qD2 Q££@fDCsc@qD2 Q@fD

in which q has been separated from f . These are the preparatory first steps in any number of physical discus-sions in which spherical (or rotational) symmetry is present (as in the quantum theory of the hydrogen atom).

Save.

Total derivatives, total differentials, fractional change

I turn now to description of a powerful little tool of many uses:

In[65]:= ? Dt

Some illustrative applications:

In[66]:= DtAx2 y3E

In[67]:= DtAx2 ynE

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 ynE ê. Dt@nD Ø 0

and in the case n=3 recover our former result:

In[70]:= % ê. n Ø 3

Here is the total time derivative of a dummy function of two variables

In[71]:= Dt@f@x, yD, tDand here is the total second derivative

In[72]:= Dt@f@x, yD, t, tDwhere

6 Laboratory 5B.nb

Page 117: Ma Thematic A Manual

Dt@x, tD means x component of velocityDt@x, tD means y component of velocityDt@x, 8t, 2<D means x component of accelerationDt@y, 8t, 2<D means y component of acceleration

Kinetic Energy of a Particle in Spherical Coordinates

We begin by recalling how the spherical coordinates were introduced:

In[73]:= Clear@x, y, z, r, q, fD

In[74]:= x@r_, q_, f_D := r Sin@qD Cos@fDy@r_, q_, f_D := r Sin@qD Sin@fDz@r_, q_, f_D := r Cos@qD

We know that in Cartesian coordinates

In[77]:= kinetricenergy =m

2 IDt@x, tD2 + Dt@y, tD2 + Dt@z, tD2M

so in spherical coordinates have

In[78]:=m

2 IDt@x@r, q, fD, tD2 + Dt@y@r, q, fD, tD2 + Dt@z@r, q, fD, tD2M êê Simplify

If you have struggled as many times as I have to recreate this important result with pen and ink you will appreci-ate the swift efficiency of the procedure just described.

Euclidean Metric in Parabolic Coordinates

We have interest in describing

squaredinterval = Dt@xD2 + Dt@yD2 + Dt@zD2

in parabolic coordinates. Recalling the definitions

In[79]:= Clear@x, y, z, u, v, fD

In[80]:= x@v_, u_, f_D := u v Cos@fDy@v_, u_, f_D := u v Sin@fDz@v_, u_, f_D :=

1

2I-u2 + v2M

we command

In[83]:= Dt@x@v, u, fDD2 + Dt@y@v, u, fDD2 + Dt@z@v, u, fDD2

In[84]:= Simplify@%DThis amounts to the statement that

Laboratory 5B.nb 7

Page 118: Ma Thematic A Manual

In[85]:= metricmatrix =

u2 + v2 0 0

0 u2 + v2 0

0 0 u2 v2êê MatrixForm

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@fDDspeaks very usefully (and dimensionlessly!) of how the a little change in f is related to the value of f . Look to the familiar relationship

In[89]:= w = L ê g ;

taken from the elementary theory of pendula. We command

In[90]:= Dt@Log@wDD êê Simplify

and learn that a 1% increase in the value of g produces a 0.5% decrease in the value of w, while a a 1% increase in the value of L produces a 0.5% increase in the value of w.

Elaborations of this basic idea permit one to describe with maximal simplicity and economy the fractional change in this that results from a fractional change in that, and are encountered also in the theory of errors.

‡ Dimensional AnalysisEngineers 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 * q1x q2y q3z

The left and right sides of the anticipated equation must be dimensionally homogeneous, which means that if

@pD = Ma Lb Tc

@q1D = Ma1 Lb1 Tc1

@q2D = Ma2 Lb2 Tc2

8 Laboratory 5B.nb

Page 119: Ma Thematic A Manual

@q3D = Ma3 Lb3 Tc3

we must have

a ã a1 x + a2 y + a3 zb ã b1 x + b2 y + b3 zc ã c1 x + c2 y + c3 z

Dimensional analysis reduces, therefore, to a problem in linear algebra (made interesting because it is "linear algebra in the exponent"). We will use Solve to tell us what the preceding equations say about the necessary values of x, y, z .

Let us, for present purposes, agree to represent the physical dimensions of things by vectors, following this convention:

mass = 81, 0, 0, 0<length = 80, 1, 0, 0<time = 80, 0, 1, 0<temperature = 80, 0, 0, 1<

And let us adopt the language of a specific example: we pretend to be freshly interested in the theory of pen-dula, and to anticipate a relationship of the form

frequency = HlengthLx HgravityLy Hmass of bobLz

We expect, in other words, to have

80, 0, -1, 0< = x 80, 1, 0, 0< + y 80, 1, -2, 0< + z 81, 0, 0, 0<

In[91]:= Solve@80, 0, -1, 0< ã x 80, 1, 0, 0< + y 80, 1, -2, 0< + z 81, 0, 0, 0<, 8x, y, z<DThe implication~already on dimensional grounds, independently of any appeal to the equations of pendular motion~is that

w = Hdimensionless numericL * HgravityL ê HlengthL

Detailed dynamical argument supplies only the information that (in small angle approximation)

dimensionless numeric = 1

To prepare for a wider range of such arguments we might define

Laboratory 5B.nb 9

Page 120: Ma Thematic A Manual

In[92]:= m = 81, 0, 0, 0< H* electron mass *L;c = 80, 1, -1, 0< H* speed of light *L;— = 81, 2, -1, 0< H* Planck's constant *L;G = 8-1, 3, -2, 0< H* gravitational constant *L;chargesquared = 81, 3, -2, 0<; H* esu electronic charge2 *L;k = 81, 2, -2, -1< H* Boltzmann's constant *L;M = 81, 0, 0, 0< H* characteristic mass *L;R = 80, 1, 0, 0< H* characteristic length *L;t = 80, 0, 1, 0< H* characteristic time *L;w = 80, 0, -1, 0< H* characteristic frequency *L;v = 80, 1, -1, 0< H* characteristic velocity *L;a = 80, 1, -2, 0< H* characteristic acceleration *L;T = 80, 0, 0, 1< H* characteristic temperature *L;energy = 81, 2, -2, 0< H* characteristic energy *L;dimensionless = 80, 0, 0, 0<;

which we might use as follows:

‡ Application to Atomic/Molecular Physics

Expected Radius of Atom

In[107]:= Solve@R ã m x + HchargesquaredL y + — z, 8x, y, z<Dwhich gives

BohrRadius =—2

m e2

Characteristic Atomic Energy

In[108]:= Solve@energy ã m x + HchargesquaredL y + — z, 8x, y, z<D

dissociationenergy =m e4

—2

Characteristic Atomic Frequency

In[109]:= Solve@w ã m x + HchargesquaredL y + — z, 8x, y, z<D

BohrFrequency =m e4

—3

Dissociation Temperature

In[110]:= Solve@T ã m x + HchargesquaredL y + — z + k u, 8x, y, z, u<D

10 Laboratory 5B.nb

Page 121: Ma Thematic A Manual

dissociationtemperature =m e4

—2 k

‡ Application to Planetary Physics

Surface Gravity

In[111]:= Solve@a ã M x + R y + G z, 8x, y, z<D

g =M G

R2

Escape Velocity from Planetary Body

In[112]:= Solve@v ã M x + R y + G z, 8x, y, z<D

escapevelocity =M G

R

‡ Application to Quantum Gravity

Planck Mass

In[113]:= Solve@M ã G x + c y + — z, 8x, y, z<D

PlanckMass =c —

G

Planck Length

In[114]:= Solve@R ã G x + c y + — z, 8x, y, z<D

PlanckLength =G —

c3

Planck Time

In[115]:= Solve@t ã G x + c y + — z, 8x, y, z<D

PlanckTime =G —

c5

Laboratory 5B.nb 11

Page 122: Ma Thematic A Manual

‡ Application to Quantum Electrodynamics

Fine Structure Constant

In[116]:= Solve@dimensionless ã — x + c y + chargesquared z, 8x, y, z<D

dimensionless =e2

— c

any power

The fine structure constant arises fron setting any power = 1.

‡ Assignment of Numerical Value in Specified UnitsThis can be accomplished with the aid of the following resources:

In[117]:= Needs@"PhysicalConstants`"DNeeds@"Units`"D

Notice that we have here found it convenient to load two packages at the same time.

In[119]:= PlanckLength =GravitationalConstant PlanckConstant

SpeedOfLight3

Unfortunately, the designer of these packages was addicted to SI units, and did not include resources powerful enough to tell us that

Joule Newton Second4

Kilogram2 Meter= Meter

To establish that fact we must import the information that

Joule = Newton Meter

Newton = Kilogram Meter Second-2

When we do so, we confirm that

In[120]:=IKilogram Meter Second-2M2 Meter Second4

Kilogram2 Meter

In[121]:= Simplify@%, Meter > 0DThe 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

12 Laboratory 5B.nb

Page 123: Ma Thematic A Manual

In[122]:=1

4 p VacuumPermittivity ElectronCharge2

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

In[123]:= a =1

4 p VacuumPermittivity ElectronCharge2

2 p

PlanckConstant SpeedOfLight

In[124]:= 1 ê %

and have to import information to demonstrate that all the dimensions cancel:

In[125]:=

CoulombSecond

Meter Newton Second

Coulomb2 Newton MeterCoulomb

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

In[126]:= numericalESUelectronicchargesquared =1

137.036 PlanckConstant

2 p SpeedOfLight

or somewhat more neatly

In[127]:= ESUelectronicchargesquared = 2.30708*^-28 Kilogram Meter3 Second-2

One then has, for example, (borrowing from our dimensional determination of the Bohr radius)

In[128]:= characteristicatomiclength =I PlanckConstant

2 pM2

ElectronMass ESUelectronicchargesquared

which in mass/length/time dimensions becomes

In[129]:=

5.29177*^-11 J Kilogram Meter

Second2N2 Second4

Kilogram2 Meter

In[130]:= CGS@%DIn the final step I have used the first of the following commands:

In[131]:= ? CGS

In[133]:= ? MKS

In[134]:= ? SI

Save.

Laboratory 5B.nb 13

Page 124: Ma Thematic A Manual

Save.

14 Laboratory 5B.nb

Page 125: Ma Thematic A Manual

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

Laboratory 6Part A

Recursive Processes

‡ BackgroundA 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@x0DD …DDIt was observed that the output converged to 0.739085 independently of the value you had assigned to the "seed" x0. This result is really not unexpected in the light of the following calculation

In[2]:= FindRoot@Cos@xD ã x, 8x, .7<Dbut 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 pointPeople 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@xDwere 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.

Page 126: Ma Thematic A Manual

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 ToolsNo longer is it necessary to "hit the Cos key many times." One can do so~proceed

In[3]:= [email protected]

In[4]:= Cos@%D

In[5]:= Cos@%D

In[6]:= Cos@%Detc., or better

In[7]:= Cos@Cos@Cos@[email protected]~but Mathematica provides tools that do such things automatically:

In[8]:= ? Nest

In[9]:= ? NestList

In[10]:= ? FixedPoint

In[11]:= ? FixedPointList

In[12]:= HPtwiddle@x_D := Cos@xD

In[13]:= Nest@HPtwiddle, 0.2, 4D

In[14]:= Nest@HPtwiddle, 0.2, 100DThere 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, 40DTry a different seed:

In[16]:= NestList@HPtwiddle, 0.9, 40DAbandon the details and proceed directly to the fixed point:

In[17]:= FixedPoint@HPtwiddle, 0.9DThe command

2 Laboratory 6A.nb

Page 127: Ma Thematic A Manual

The command

In[18]:= FixedPointList@HPtwiddle, 0.9Dyields 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

In[19]:= CobwebPlot@f_, 8x_, a_, b_<, x0_, n_IntegerD :=

CobwebPlot@f, 8x, a, b<, x0, 80, n<D

In[20]:= CobwebPlot@f_, 8x_, a_, b_<, x0_, 8n0_, n_<D :=

Module@8data, fcn<,fcn = Compile@x, fD;data = NestList@fcn, s = Nest@fcn, x0, n0D, n - 1D;y0 = If@n0 ã 0, 0, sD;Show@Block@8$DisplayFunction = Identity<,

8Plot@f, 8x, a, b<D,Graphics@[email protected], Line@Drop@Prepend@

Flatten@data ê. z_?NumericQ :> 88z, ff = fcn@zD<, 8ff, ff<<, 1D, 8s, y0<D,

-1DD<, [email protected], Point@8s, y0<D<, [email protected],Line@88a, a<, 8b, b<<D<<D<D, PlotRange Ø 88a, b<, All<DD

Wagon's creation works like this:

In[21]:= CobwebPlot@HPtwiddle@xD, 8x, 0, p ê 2<, 0.2, 15DLet 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, 15DTry a different map:

In[23]:= twiddlediddle@x_D := Sin@xD

Laboratory 6A.nb 3

Page 128: Ma Thematic A Manual

In[24]:= CobwebPlot@twiddlediddle@xD, 8x, 0, p<, 1.0, 15D

In[25]:= CobwebPlot@twiddlediddle@xD, 8x, 0, p<, 2.0, 15DOr this variant of that map:

In[26]:= CobwebPlot@2 twiddlediddle@xD, 8x, 0, p<, 2.0, 15D

In[27]:= CobwebPlot@3 twiddlediddle@xD, 8x, 0, p<, 2.0, 15DNo fixed point is now in evidence. CobwebPlot permits us to iterate (let us say) 275 times, but show only the last 75; to get an improved sense of what's going on, let's do so

In[28]:= CobwebPlot@3 twiddlediddle@xD, 8x, 0, p<, 2.0, 8200, 75<D

‡ Logistic Map: Bifurcation and the Onset of ChaosIn Laboratory 4 we encountered the "logistic equation" (also called the Verhulst equation)

x'@tD ã x@tD H1 - x@tDLthat describes population growh with saturation (Verhulst process), which is characteristically "sigmoid":

In[29]:= DSolve@8x'@tD ã x@tD H1 - x@tDL, x@0D ã 0.1<, x@tD, tD

In[30]:= logisticpopulation@t_D :=‰t

9.` + ‰t

In[31]:= exact =

Plot@logisticpopulation@tD, 8t, -5, 10<, PlotStyle Ø 8RGBColor@0, 0, 1D<DIf we were motivated to solve the logistic equation numerically we would write

x@t + tD = x@tD + t x@tD H1 - x@tDLx@0D = 0.1

and iterate. We are in position not to discuss very simply what would result from such a procedure:

In[32]:= Logistic@x_D := x +1

10x H1 - xL

In[33]:= values = NestList@Logistic, 0.1, 100D

In[34]:= timepoints = TableB i

10, 8i, 0, 100<F

Digression: How to make a binary list from two lists

The following remarks are, I think, self-explanatory: define

In[35]:= firstlist = 8a1, a2, a3<

4 Laboratory 6A.nb

Page 129: Ma Thematic A Manual

In[36]:= secondlist = 8b1, b2, b3<Recall that the suffix PkT serves to pluck the kth element out of a list: thus

In[37]:= firstlistP3T(Recall also that P is produced Â[[Â .) Construct

In[38]:= binarylist = Table@8firstlistPkT, secondlistPkT<, 8k, 1, 3<Dwhich is a list of binary lists, with first element taken from firstlist, and second element taken from secÖ

ondlist. There is, however, a much better way (which, I am embarrassed to report, I learned only after this text was drafted, while preparing the exercises): simply command

In[39]:= Transpose@8firstlist, secondlist<D

In[40]:= ? Transpose

The official description is not very clear, but the command clearly does job, and very efficiently. Here ends the digression.

Using the technique just described (I use the first technique, but recommend that you in such contexts use Transpose), we create the binary table

In[41]:= logisticdata = Table@8timepointsPkT, valuesPkT<, 8k, 1, 100<Dand use ListPlot to display that data:

In[42]:= approximate = ListPlot@logisticdataD

In[43]:= Show@exact, approximateDMight we have taken bigger t-steps and, with less labor, still have obtained a satisfactory result? Back up and retrace our steps:

In[44]:= Logistic2@x_D := x +1

2x H1 - xL

In[45]:= values2 = NestList@Logistic2, 0.1, 20D

In[46]:= timepoints2 = TableBi2, 8i, 0, 20<F

In[47]:= logisticdata2 = Table@8timepoints2PkT, values2PkT<, 8k, 1, 20<D

In[48]:= approximate2 = ListPlot@logisticdata2D

In[49]:= Show@exact, approximate2DPretty good!…though little errors are now evident.

Save.

If we had serious interest in numerical solution of the logistic ODE we would be making t smaller and smaller. But~our curiosity whetted~we abandon the ODE to concentrate on the logistic map itself, looking especially to its asymptotic properties. We try a really big t (t = 1.8 )

Laboratory 6A.nb 5

Page 130: Ma Thematic A Manual

If we had serious interest in numerical solution of the logistic ODE we would be making t smaller and smaller. But~our curiosity whetted~we abandon the ODE to concentrate on the logistic map itself, looking especially to its asymptotic properties. We try a really big t (t = 1.8 )

In[50]:= Logistic3@x_D := x + 1.8 x H1 - xL

In[51]:= values3 = NestList@Logistic3, 0.1, 50D

In[52]:= ListPlot@values3, PlotRange Ø 80, 1.5<,AxesLabel Ø 8iterations, None<,PlotLabel Ø FontForm@"Logistic map with t = 1.800", 8"Helvetica", 16<D,Ticks Ø 8Automatic, 81<<D

and find that the iterative process still approaches 1.00000 asymptotically (as a fixed point). But at t = 2.0

In[53]:= Logistic4@x_D := x + 2.0 x H1 - xL

In[54]:= values4 = NestList@Logistic4, 0.1, 50D

In[55]:= ListPlot@values4, PlotRange Ø 80, 1.5<,AxesLabel Ø 8iterations, None<,PlotLabel Ø FontForm@"Logistic map with t = 2.000", 8"Helvetica", 16<D,Ticks Ø 8Automatic, 81<<D

we are led asymptotically to an alternating pair of points. And at t = 2.542

In[56]:= Logistic5@x_D := x + 2.542 x H1 - xL

In[57]:= values5 = NestList@Logistic5, 0.1, 50D

In[58]:= ListPlot@values5, PlotRange Ø 80, 1.5<,AxesLabel Ø 8iterations, None<,PlotLabel Ø 8"Logistic map with t = 2.542"<,Ticks Ø 8Automatic, 81<<D

we are led asymptotically to a quartet of points that present themselves in a fixed cyclic order.

CobwebPlot can be used to clarify the situation: we define

In[59]:= logisticmap@t_D@x_D := x + t x H1 - xLand proceed

In[60]:= CobwebPlot@[email protected]@xD, 8x, 0, 1.5<, 0.1, 50Dwhich 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@[email protected]@xD, 8x, 0.8, 1.2<, 0.1, 840, 10<D~while at t = 2.0 we find

In[62]:= CobwebPlot@[email protected]@xD, 8x, 0, 1.5<, 0.1, 50D

6 Laboratory 6A.nb

Page 131: Ma Thematic A Manual

In[63]:= CobwebPlot@[email protected]@xD, 8x, 0.8, 1.2<, 0.1, 840, 10<Dthat 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@[email protected]@xD, 8x, 0, 1.5<, 0.1, 50D

In[65]:= CobwebPlot@[email protected]@xD, 8x, 0.4, 1.4<, 0.1, 840, 10<D

Save.

‡ Bifurcation PlotIt becomes natural at this point to try something like the following: (1) assign a value to t; (2) iterate long enough (say 1000 steps) until things have stabilized, then record something like 100 consecutive values; (3) increment the value of t and do the whole thing over again; (4) plot the data thus generated.

What follows is a good example of grown-up Mathematica programming. Just as Bach learned by copying out (and then writing variations upon) Vivaldi scores, so would you learn some things by typing with your own hand the code. Try it sometime. You will, at the very least, be reminded how difficult it is to type accurately; Mathematica is quite unforgiving~requires every bracket, every bit of punctuation, every capital to be exactly right…and usually provides no clue as to where you have made your error. It is much easier to type correctly than to edit in search of typos.

In[66]:= Needs@"Utilities`FilterOptions`"D;

In[67]:= elimDups@v_D := Module@8d = Sort@vD<,Union@FoldList@If@Ò2 < 0.001 + Ò1, Ò1, Ò2D &, First@dD, Rest@dDDDD;

In[68]:= Options@BifurcationPlotD = 8PlotPoints Ø 100<;

In[69]:= BifurcationPlot@f_, 8r_, a_, b_<, 8x_, x0_<, 8iter0_, iterShow_<, opts___D :=

ModuleB8n<, n = PlotPoints ê. 8opts< ê. Options@BifurcationPlotD;makePts@8s_, v_<D := HPoint@8s, Ò1<D &L êü v;

cf = Compile@88r, _Real, 1<, 8x, _Real, 1<<, Evaluate@fDD;rVals = HMin@Ò1, bD &L êü RangeBN@aD, b, NBb - a

n - 1FF;

data = Transpose@8rVals, elimDups êü Transpose@NestList@cf@rVals, Ò1D &,Nest@cf@rVals, Ò1D &, Array@x0 &, nD, iter0D, iterShowDD<D;

Show@Graphics@[email protected]`D, makePts êü data<D,Sequence üü FilterRules@Flatten@8opts<D, Options@GraphicsDD,Frame Ø True, PlotRange Ø 88a, b<, All<DF;

The program works like this:

In[71]:= logisticmap@r_D@x_D := x + r x H1 - xL

In[72]:= BifurcationPlot@logisticmap@rD@xD, 8r, 1.8, 3<, 8x, 0.1<, 8500, 10<,PlotPoints Ø 1000D

Drag to nearly page-width to get a better view.

Laboratory 6A.nb 7

Page 132: Ma Thematic A Manual

Drag to nearly page-width to get a better view.

Save.

We see that 1 is a fixed point until the control parameter r approaches 2, when the fixed point bifurcates (this is called a "pitchfork bifurcation"). We then have a 2-cycle until r approaches about 2.45, when a second bifurca-tion gives rise to a 4-cycle. We then pass rapidly through ascending powers of 2 until at about r = 2.58 we enter a chaotic regime…which appears to be punctuated occasionally with "islands of cyclicity."

If we expand the view of the 2nd & 3rd orders of bifurcation (this is done simply by reducing the distance between rmin and rmax) we get the impression that they are just miniature copies of the initial bifurcation; i.e., that a principle of self-similarity is operative.

In[73]:= BifurcationPlot@logisticmap@rD@xD, 8r, 2.4, 2.6<, 8x, 0.1<, 8500, 10<,PlotPoints Ø 1000,GridLines Ø 882.448, 2.544, 2.565<, None<,PlotRange Ø 80, 1.4<D

It was from an initial version of this figure that I determined where to place the gridlines that mark bifurcation points. Those were improved with a couple generations of trial and error.

When we try to obtain a magnified view of the first pair of "islands of cyclicity"

In[74]:= BifurcationPlot@logisticmap@rD@xD, 8r, 2.6, 2.8<, 8x, 0.1<, 8500, 10<,PlotPoints Ø 1000,GridLines Ø 882.630, 2.742<, None<,PlotRange Ø 80, 1.4<D

an intermediate island comes into view, which we look at more closely:

In[75]:= BifurcationPlot@logisticmap@rD@xD, 8r, 2.69, 2.71<, 8x, 0.1<, 8500, 10<,PlotPoints Ø 1000,GridLines Ø 882.7022<, None<,PlotRange Ø 80, 1.4<D

We have discovered a 7-cycle, bracked on the left by a 6-cycle, and on the right by a 5-cycle. Look to the associated cobweb plot:

In[76]:= CobwebPlot@[email protected]@xD, 8x, 0.2, 1.4<, 0.1, 8200, 30<DEvidently 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:

8 Laboratory 6A.nb

Page 133: Ma Thematic A Manual

In[77]:= BifurcationPlot@logisticmap@rD@xD, 8r, 2.8, 2.9<, 8x, 0.1<, 8500, 10<,PlotPoints Ø 1000,GridLines Ø 882.835<, None<,PlotRange Ø 80, 1.4<D

Drag to size.

and to the associated cobweb:

In[78]:= CobwebPlot@[email protected]@xD, 8x, 0.1, 1.4<, 0.1, 840, 10<DIn this case we see very clearly a miniaturized replication of the original family of pitchforks.

Working from such enlargements, I have located the low-order bifurcation points, and have in the next figure used that improved data + higher resolution to place grid lines that show a bit better what is going on:

In[79]:= BifurcationPlot@logisticmap@rD@xD, 8r, 1.8, 3<, 8x, 0.1<, 8500, 10<,PlotPoints Ø 1500,FrameTicks Ø 881.996, 2.448, 2.543, 2.835<, Automatic, None, None<,GridLines Ø 881.996, 2.448, 2.544, 2.565, 2.835<, None<D

Drag to size.

The following calculations

In[80]:= :2.4481.996

,2.544

2.448,2.565

2.544>

In[81]:= Log@%D

In[82]:= 90.204126, 0.2041262, 0.2041263=

suggest that the placement of successive bifurcation points conforms to a simple pattern

Log@r2D = Log@r1D + k with k = 0.204126Log@r3D = Log@r2D + k2 = Log@r1D + k + k2

Log@r¶D = Log@r1D + k + k2 + k3 + ... = Log@r1D +k

1 - k

On this basis we expect onset of chaos to occur at

In[83]:= r¶ = 1.996 ‰0.204126

1-0.204125

which looks to be about right. Down this road lies the universal Feigenbaum number 4.669…, which was discovered by Michael Feigenbaum in 1975.

Save.

Laboratory 6A.nb 9

Page 134: Ma Thematic A Manual

Comparison with a Couple of Other Maps: First Glimpse of "Universality"

Other maps gives rise to events which~remarkably~follow the same general pattern:

In[84]:= quadraticmap@r_D@x_D := r x H1 - xL

In[85]:= BifurcationPlot@quadraticmap@rD@xD, 8r, 2.8, 4<, 8x, 0.5<, 8500, 10<,PlotPoints Ø 1000D

In[86]:= sinemap@r_D@x_D := r Sin@p xD

In[87]:= BifurcationPlot@sinemap@rD@xD, 8r, 0.6, 1<, 8x, 0.5<, 8500, 10<,PlotRange Ø 80, 1<, PlotPoints Ø 1000D

These figures have become icons of late 20th-Century mathematics. Another is the Mandelbrot Set, which arises from iteration of the complex quadratic map

z Ø z2 + a

They speak simultaneously of

• bifurcation (successive generations of bifurcation);

• the abrupt onset of chaos (and its occasional~equally abrupt~disappearance);

• cryptic universality…

These notions live not only in the world of mathematical abstraction; symptoms of them have been found to be all around us in the physical world, now that we have acquired eyes to see them. They can be found in physics (in all of its flavors), biology, economics…and have become indispensable players in any modern conception of "how the world works."

Coupled Nonlinear ODEs with Chaotic Solutions

We are in the habit of considering the world~those parts of it of greatest interest to physicists~to be described not by iterated maps but by differential equations. It has only in fairly recent times come to be widely appreci-ated (though it was evident to Poincare already a century ago) that fairly simple systems of coupled ODEs can have wildly irregular solutions~solutions that depend very critically upon the prescribed initial conditions. I give two examples:

Save.

10 Laboratory 6A.nb

Page 135: Ma Thematic A Manual

‡ Rikitake's Model of Geomagnetic Field ReversalIn 1958, T. Rikitake (Proc. Camb. Phil. Soc. 54, 89|105) used a simple coupled disk dynamo system to model the generation of the earth's magnetic field (see my Classical Electrodynamics 1980, page 139 or §6.1 in S. Neil Rasband's Chaotic Dynamics of Nonlinear Systems 1990 for details; also the final pages of H. K. Moffatt, Magnetic Field Generation in Electrically Conducting Fluids 1978). He was led to the following system of coupled 1st order nonlinear ODEs:

x'@tD ã -m x@tD + u@tD y@tDy'@tD ã -a x@tD - m y@tD + u@tD x@tDu'@tD ã 1 - x@tD y@tDm > 0 and a > 0 are parameters

It is easy enough for Mathematica to solve such coupled ODEs. Preliminar experimentation leads us to assign illustrative values of 1.0 and 2.7 to m and a, and initial values of 1.0, 0 and 0.5 to x, y and u; we then obtain

In[88]:= numsoln = NDSolve@8x'@tD ã -x@tD + u@tD y@tD,y'@tD ã -2.7 x@tD - y@tD + u@tD x@tD,u'@tD ã 1 - x@tD y@tD,x@0D ã 1.0,y@0D ã 0,u@0D ã 0.5<, 8x, y, u<, 8t, 0, 200<, MaxSteps Ø 6000D

Mathematica reported itself unable to do what we had commanded with the 1000 default MaxSteps value. So we increased it.

How to display the numerical information which Mathematica has now at its disposal? Rikitaki himself plotted

In[89]:= Plot@Evaluate@x@tDD ê. %, 8t, 0, 200<, PlotRange Ø AllDand

In[90]:= ParametricPlot@Evaluate@8x@tD, u@tD< ê. numsolnD,8t, 0, 200<, PlotPoints Ø 2000D

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:

In[91]:= rikitakebutterfly = ParametricPlot3D@Evaluate@8x@tD, y@tD, u@tD< ê. numsolnD, 8t, 0, 200<, PlotPoints Ø 2000,AxesLabel Ø 8"x", "y", "u"<D

Laboratory 6A.nb 11

Page 136: Ma Thematic A Manual

Save.

This result provides a nice opportunity to exploit Mathematica's Live3D capability.

In[93]:= rikitakenoticks = ParametricPlot3D@Evaluate@8x@tD, y@tD, u@tD< ê. numsolnD, 8t, 0, 200<, PlotPoints Ø 2000,Ticks Ø NoneD;

‡ Lorenz ModelGentle 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@tDy'@tD ã r x@tD - y@tD - r x@tD z@tDz'@tD ã x@tD y@tD - b z@tDs > 0, r and b > 0 are parameters

which in their general features are somewhat reminiscent of Rikitaki's equations. Managing the Lorenz' equa-tions as we managed Rikitake's, and setting our parameters/initial data to agree with page 893 of The Mathemat-ica Book (where this example illustrates the use of NDSolve), we proceed

In[95]:= lorenz = NDSolve@8x'@tD ã -3 x@tD + 3 y@tD,y'@tD ã 26.5 x@tD - y@tD - u@tD x@tD,u'@tD ã x@tD y@tD - u@tD,x@0D ã 0,y@0D ã 1,u@0D ã 0<, 8x, y, u<, 8t, 0, 20<, MaxSteps Ø 3000D

In[96]:= Plot@Evaluate@x@tDD ê. %, 8t, 0, 20<, PlotRange Ø AllD

In[97]:= ParametricPlot@Evaluate@8x@tD, u@tD< ê. lorenzD, 8t, 0, 20<, PlotPoints Ø 2000D

In[98]:= ParametricPlot3D@Evaluate@8x@tD, y@tD, u@tD< ê. lorenzD,8t, 0, 20<, PlotPoints Ø 2000,AxesLabel Ø 8"x", "y", "u"<D

The qualitative resemblance to results obtained from the (much less well studied) Rikitake model is striking. We again detect the scent of some kind of "universality" principle…in which connection we note that both systems are (not obviously, the way I have presented them) nonlinear forced dissipative systems.

I will not pursue this rich topic, because to do so would risk being seduced by the physics, and our present assignment is simply to become acquainted with the utility of Mathematica. So I leave the Poincare maps, Liapunov exponents, etc. for you to explore on your own, if someday you are so inclined.

You will appreciate that DEs are like iterated maps, in that they tell the state point where to go, where to go, where to go… And that such rich structure as we have seen is exposed only by numerical analysis (which Mathematica takes in easy stride). And the moral if it all: simple rules can have inexhaustibly complex consequences.

12 Laboratory 6A.nb

Page 137: Ma Thematic A Manual

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.

Laboratory 6A.nb 13

Page 138: Ma Thematic A Manual

Physicist's Introduction to MathematicaLaboratory 6Part B

Fitting Curves to Data

‡ Preliminary RemarksIt 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`"Dyou 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).

Page 139: Ma Thematic A Manual

‡ Curve-fitting TechniquesWe begin by creating some artificial "data":

In[3]:= data = TableA9x, Sin@xD - Cos@xD + LogA1 + x2E=, 8x, 0, 12, 1<E êê N

Try first this simple device, which we encountered already in Lab 1:

In[4]:= ? ListPlot

In[5]:= ListPlot@data, Joined Ø True, Epilog Ø [email protected]`D, Point êü data<DHere as always~when mystified by details in a sample command (here: the PlotJoined option, the use of Epilog and the meaning of /@), we can ask Mathematica about them:

In[6]:= Options@ListPlotD

In[7]:= ? Epilog

In[8]:= ? êü

Just as easy to use but in most applications more interesting~and certainly more powerful (it contains the preceding as a special case)~is the command

In[9]:= ? Interpolation

that asks Mathematica to use its smarts to come up with a "best" interpolation (which Mathematica does by using piecewise cubic curves; we'll see in a moment what that means):

In[10]:= func = Interpolation@dataD

In[11]:= Plot@Evaluate@func@xDD, 8x, 0, 12<DLooks to be a pretty good fit. How good? Superimpose the data points:

In[12]:= Plot@Evaluate@func@xDD, 8x, 0, 12<,Epilog Ø [email protected], Point êü data<D

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:

In[13]:= Plot@Evaluate@func@xDD, 8x, -2, 14<,Epilog Ø [email protected], Point êü data<D

The interpolated function can, for most purposes, be treated like any other function; thus

In[14]:= func@10D

In[15]:= ‡0

12

func@xD „x

In[16]:= FindRoot@func@xD ã 4, 8x, 6<DWe are, in fact, already familiar with such objects: they are produced by (for example) NDSolve .

2 Laboratory 6B.nb

Page 140: Ma Thematic A Manual

We are, in fact, already familiar with such objects: they are produced by (for example) NDSolve .

When we ask Mathematica about

In[17]:= Options@InterpolationDwe 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

In[19]:= Plot@Evaluate@func1@xDD, 8x, 0, 12<,Epilog Ø [email protected], Point êü data<D

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

‚data points

Hdata - linear approximantL2 = minimum

with the following very powerful command:

In[20]:= ? Fit

In[21]:= linearFit = Fit@data, 81, x<, xDThe highlighted detail asks Mathematica to do its best to fit the data to a curve of the form

a0 + a1 x

~which is just what Mathematica did. Look at the result:

In[22]:= Plot@linearFit, 8x, 0, 12<, Epilog Ø [email protected], Point êü data<,PlotRange Ø 8-2, 8<D

Try a 4th order polynomial:

In[23]:= quadricFit = FitAdata, 91, x, x2, x3, x4=, xE

In[24]:= Plot@quadricFit, 8x, 0, 12<, Epilog Ø [email protected], Point êü data<,PlotRange Ø 8-2, 8<D

Try 8th order:

In[25]:= degreeEightFit = FitAdata, 91, x, x2, x3, x4, x5, x6, x7, x8=, xE

In[26]:= Plot@degreeEightFit, 8x, 0, 12<, Epilog Ø [email protected], Point êü data<,PlotRange Ø 8-2, 8<D

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

Laboratory 6B.nb 3

Page 141: Ma Thematic A Manual

In[27]:= devilsFit = FitAdata, 9Sin@xD, Cos@xD, LogA1 + x2E=, xE

and thus recover precisely the function we originally used to generate our toy data! A less insightful mathemati-cian might have tried (say)

In[28]:= devilsapprenticeFit = FitAdata, 9Sin@xD, Cos@xD, 1, x2=, xE

In[29]:= Plot@devilsapprenticeFit, 8x, 0, 12<,Epilog Ø [email protected], Point êü data<,PlotRange Ø 8-2, 8<D

which is nothing to write home about.

Digression: Surpression of an Artifact

Use a polynomial to generate some toy data

In[30]:= polynomialdata = TableA9x, 6 x + x2=, 8x, 0, 12, 1<E êê N

and try to fit that data to (say) a quintic:

In[31]:= quinticFit = FitApolynomialdata, 91, x, x2, x3, x4, x5=, xE

The coefficients of x0, x3, x4 and x5~which should ideally be 0~are in fact tiny non-zero numbers (artifacts of the numerical data-fitting process). Mathematica provides means to surpress such artifacts:

In[32]:= Chop@%D

In[33]:= ? Chop

Fourier Analytic Curve Fitting

Suppose our data were known/suspected on some grounds to be periodic:

In[34]:= periodicdata = 880., 2.5<, 81., 1.994315859499702<, 82., 2.9348821758069246<,83., 3.4336975976543584<, 84., 2.7300544696118996<,85., 2.0155100778951174<, 86., 2.3713321277949326<,87., 3.8151073498036303<, 88., 5.309245550327632<,89., 5.7299679943906865<, 810., 4.910170935028343<,811., 3.7996051401945024<, 812., 3.596306865687647<,813., 2.5<, 814., 1.994315859499702<, 815., 2.9348821758069246<,816., 3.4336975976543584<, 817., 2.7300544696118996<,818., 2.0155100778951174<, 819., 2.3713321277949326<,820., 3.8151073498036303<, 821., 5.309245550327632<,822., 5.7299679943906865<, 823., 4.910170935028343<,824., 3.7996051401945024<, 825., 3.596306865687647<<

Working by hand, I have duplicated our original data set, then modified the data at x=0 and x=1 to ellimiinate awkward "outliers."

4 Laboratory 6B.nb

Page 142: Ma Thematic A Manual

In[35]:= Show@Graphics@[email protected], Point êü periodicdata<DDIt would then be natural to try

In[36]:= fourierFit = FitBperiodicdata, :

CosB0 2 p

13 xF, SinB0

2 p

13 xF,

CosB1 2 p

13 xF, SinB1

2 p

13 xF,

CosB2 2 p

13 xF, SinB2

2 p

13 xF,

CosB3 2 p

13 xF, SinB3

2 p

13 xF,

CosB4 2 p

13 xF, SinB4

2 p

13 xF>, xF

The following figure

In[37]:= Plot@fourierFit, 8x, 0, 24<,Epilog Ø [email protected], Point êü periodicdata<,PlotRange Ø 8-2, 8<D

shows the result (not remarkably, since we have used 10 functions to fit 13 data points) to be quite good.

Extrapolation

On the following evidence

In[40]:= Plot@fourierFit, 8x, 0, 37<,Epilog Ø [email protected], Point êü periodicdata<,PlotRange Ø 8-2, 8<D

we infer that Mathematica, though reluctant to extrapolate on the basis of Interpolate, is happy to do so on the basis of information produced by Fit .

Now You're On Your Own: Good Luck!

I promised to "scratch the surface" of Mathematica. We have done that, but barely. Spend some time perusing The Mathematica Book, the Standard Packages book and various commercial user guides (some are quite specialized, bearing titles like "Mathematica in the Laboratory") to glimpse the vast wealth of material we have altogether bypassed.

I will have succeeded if you carry away from these exercises a sense that Mathematica is a powerful tool, relevant to the stuff that physicists do; that it is an approachable resource (and of how to approach it); that it is fun; that it permits you to approach applied mathematics in an "experimental" frame of mind.

Laboratory 6B.nb 5

Page 143: Ma Thematic A Manual

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.

6 Laboratory 6B.nb