computational physics 330 - physics and astronomy - brigham

87
C OMPUTATIONAL P HYSICS 330 NON-L INEAR DYNAMICS AND DIFFERENTIAL E QUATIONS Ross L. Spencer and Michael Ware Department of Physics and Astronomy Brigham Young University

Upload: others

Post on 11-Feb-2022

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: computational physics 330 - Physics and Astronomy - Brigham

COMPUTATIONAL PHYSICS 330

NON-LINEAR DYNAMICS AND DIFFERENTIAL EQUATIONS

Ross L. Spencer and Michael Ware

Department of Physics and AstronomyBrigham Young University

Page 2: computational physics 330 - Physics and Astronomy - Brigham
Page 3: computational physics 330 - Physics and Astronomy - Brigham

COMPUTATIONAL PHYSICS 330

NON-LINEAR DYNAMICS AND DIFFERENTIAL EQUATIONS

Ross L. Spencer and Michael Ware

Department of Physics and AstronomyBrigham Young University

Last revised: September 5, 2014

© 2005–2014 Ross L. Spencer, Michael Ware, and Brigham Young University

Our objective in this course is to learn how to use a symbolic mathematicsprogram and programming in Matlab to analyze physics problems in terms ofordinary differential equations and solve them numerically. The instructor andteaching assistants will highlight the important ideas and to coach you throughthe laboratory exercises. This is not an independent study course. Studentswho try to work through this material on their own usually spend many hourslooking for trivial programming mistakes and consequently don’t have time tolearn the nonlinear dynamics which is at the heart of the course. Attendance atthe scheduled lab periods is critical.

We assume that you are familiar with Mathematica from the start so that ourstudy of differential equations can begin in this language. Initially the labs consistof Mathematica exercises involving differential equations and assignments towork through sections of the text Introduction to Matlab. Later we use bothMatlab and Mathematica to study nonlinear dynamics, including entrainment,limit cycles, period doubling, intermittency, chaos, ponderomotive forces, andhysteresis using Matlab. This course only provides a very brief introduction tononlinear dynamics. To master this subject, you should pursue independentreading and take more complete courses in the subject.

Suggestions for improving this manual are welcome. Please direct them toMichael Ware ([email protected]).

Page 4: computational physics 330 - Physics and Astronomy - Brigham
Page 5: computational physics 330 - Physics and Astronomy - Brigham

Contents

Table of Contents v

1 Differential Equations and Baseball 1Differential Equations in Mathematica . . . . . . . . . . . . . . . . . . . 1Baseball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Introduction to Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Qualitative Analysis and Matlab 7How does a differential equation make a curve? . . . . . . . . . . . . . . 7Matlab Scripting Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Loops, Logic, and Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

3 Phase Space 11Loops and Logic Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Surface and Flow Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Phase Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

4 Calculus and a Bouncing Ball 15Calculus on a Discrete Grid . . . . . . . . . . . . . . . . . . . . . . . . . . 15Roundoff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Solving Differential Equations Numerically . . . . . . . . . . . . . . . . 16

5 Matlab’s ODE Solvers and Meteorites 19Functions in Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Numerically Solving Differential Equations . . . . . . . . . . . . . . . . 20

6 The Harmonic Oscillator and Resonance 25The Basic Oscillator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25The Damped Oscillator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Phase Space Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27The Driven, Damped Oscillator . . . . . . . . . . . . . . . . . . . . . . . 27Resonance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28Resonance Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

7 The Pendulum 31Period and Frequency of the Pendulum . . . . . . . . . . . . . . . . . . . 31

v

Page 6: computational physics 330 - Physics and Astronomy - Brigham

Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Curve Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

8 Fourier Transforms 35Interpolation and Extrapolation . . . . . . . . . . . . . . . . . . . . . . . 35Fourier Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35FFTs and Fourier Transforms . . . . . . . . . . . . . . . . . . . . . . . . . 35The Uncertainty Principle . . . . . . . . . . . . . . . . . . . . . . . . . . . 36Windowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

9 Pumping a Swing 39Pumping With Angular Momentum . . . . . . . . . . . . . . . . . . . . . 39Pumping With Parametric Oscillations . . . . . . . . . . . . . . . . . . . 41Interpreting the Spectrum of the Parametric Oscillator . . . . . . . . . . 42

10 Chaos 47The van der Pol Oscillator . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Limit Cycles and Attractors . . . . . . . . . . . . . . . . . . . . . . . . . . 47Entrainment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Dynamical Chaos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Intermittency, 1/ f Noise, and the Butterfly Effect . . . . . . . . . . . . . 50Fractals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

11 Coupled Nonlinear Oscillators 53Coupled Equations of Motion via Lagrangian Dynamics . . . . . . . . . 53Coupled Wall Clocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55Solving Nonlinear Equations . . . . . . . . . . . . . . . . . . . . . . . . . 56

12 The Pendulum with a High Frequency Driving Force 59Perturbation Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59Driven Pendulum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60Publication Quality Plots (Optional) . . . . . . . . . . . . . . . . . . . . . 62

13 Two Gravitating Bodies 63Center of Mass Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . 64Kepler’s Laws . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

14 Hysteresis in Nonlinear Oscillators 69Qualitative Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Mathematica Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Matlab Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Index 81

Page 7: computational physics 330 - Physics and Astronomy - Brigham

Lab 1

Differential Equations and Baseball

Differential equations are the language of physics. To this point, you haveprobably focused on systems where the differential equations can be solvedanalytically to obtain an explicit formula describing the dynamics. However,there is literally a world of interesting systems for which it is not possible to obtainsimple formulas for the dynamics. In this course we use numerical methods toexplore such systems.

Differential Equations in Mathematica

Mathematica has some excellent differential equation solvers built into it, bothanalytic and numerical.

P1.1 Read the section titled “Symbolic solutions to ordinary differential equa-tions” in the Mathematica tutorial Differential equations with Mathematica(available on the Physics 330 course web page).

P1.2 Use Mathematica to solve the differential equation governing the currenti (t ) in a circuit containing a battery of emf E , resistance R , and inductanceL is1

L

(d

d ti (t )

)+Ri (t ) = E (1.1)

Use Mathematica to solve this differential equation for the current and plotthe result if the initial current is zero, L = 0.001 H, R = 100Ω, and E = 6 V.

HINT: When choosing the plot range, look at the solution and notice thatthe time constant for an RL circuit is τ= L/R.

P1.3 Use Mathematica to solve the following differential equations in generalform (no initial conditions).

(a) Bessel’s Equation

x2(

d 2

d x2 f (x)

)+x

(d

d xf (x)

)+ (x2 −n2) f (x) = 0

(b) Legendre’s Equation

(1−x2)

(d 2

d x2 f (x)

)−2x

(d

d xf (x)

)+n(n +1) f (x) = 0

1Perhaps you are wondering why we aren’t using I (t ) for the current. Recall that I is the imaginarynumber (

p−1) in Mathematica, so we don’t want to use this symbol for anything else.

1

Page 8: computational physics 330 - Physics and Astronomy - Brigham

2 Computational Physics 330

P1.4 Read the section titled “Numerical solutions to ordinary differential equa-tions” in the Mathematica tutorial Differential equations with Mathematica.

(a) Ask Mathematica to solve the following differential equation symboli-cally and see what happens.

d 2

d x2 y(x) = 10sin(y (x)

)(1.2)

Now write the equation as a first order set, and solve it numericallywith y(0) = 0 and v(0) ≡ y ′(0) = 0.1. Plot y(x) from x = 0 to x = 10.

(b) Determine what a rocket’s initial velocity would need to be if launchedvertically away from the earth’s surface for it to just reach the moonat z = 3.8×108 m before falling back to earth. How long would therocket take to get to the moon?

HINT: The escape velocity from the earth’s surface is about 11,200 m/s,so your velocity will be less than this. Also, if you let time run too long,NDSolve will break because the differential equation has a zero in thedenominator. Just run time out long enough to get the projectile tothe apex of its flight.

Baseball

In Physics 121 you did the problem of a hard-hit baseball, but because you didit without air friction you were playing baseball on the moon. Let’s play ball in areal atmosphere now. The air-friction drag2 on a baseball is approximately givenby the following formula

Fdrag =−1

2Cdρairπa2|v|v (1.3)

where Cd is the drag coefficient, ρair is the density of air, a is the radius of the ball,and v is the vector velocity of the ball. The absolute value in Eq. (1.3) pretty muchguarantees that we won’t find a formula for the solution of this problem, but that’sfine since we know how to numerically solve differential equations now.

There are two forces acting on a baseball: air drag and gravity. Using Newton’ssecond law mr =∑

F, we see that equation of motion for the ball is

mr = Fdrag −mg y (1.4)

where r is the vector position of the ball, m is the mass of the baseball, g is theacceleration of gravity, and we have chosen the y direction to be up. Since this is

2For more information about the subject of air drag see R. Baierlein, Newtonian Dynamics(McGraw Hill, New York, 1983), p. 1-7, and G. Fowles and G. Cassiday, Analytical Mechanics(Saunders, Fort Worth, 1999), p. 55-65.

Page 9: computational physics 330 - Physics and Astronomy - Brigham

Lab 1 Differential Equations and Baseball 3

a vector equation, it represents a system of equations—one for each dimension.To simplify our life, let’s consider the motion to be just in the x-y plane with x asthe horizontal direction. Using the definition of velocity, we can convert Eq. (1.4)into the following set of four coupled first-order equations

d x

d t= vx

d vx

d t=−

Cdρairπa2vx

√v2

x + v2y

2m

d y

d t= vy

d vy

d t=−

Cdρairπa2vy

√v2

x + v2y

2m− g

(1.5)

Figure 1.1 The trajectory for ahome run hit, including the effectof air friction. Note that the path isnot a parabola.

P1.5 (a) Use Mathematica to solve the set of equations (1.5) for a baseball withthe following parameters:

Cd = 0.35 ρair = 1.2 kg/m3

a = 0.037 m m = 0.145 kg

g = 9.8 m/s2

Put the point of contact between bat and ball at the origin (x(0) = 0,y(0) = 0). Write your initial conditions in terms of the initial angle θand velocity v0 of the baseball (i.e. v0x = v0 cosθ, v0y = v0 sinθ) so wecan play with the angle and initial speed.

Plot y(t ) and x(t ) for the initial conditions of θ = 45 and v0 = 60 m/s.Then plot the trajectory y(t ) vs. x(t ) using ParametricPlot.

HINT: If you get your numeric solutions for x(t) and y(t) out of thesolution list like this

xpos = x[t] /. sols

ypos = y[t] /. sols

then you’ll need to Flatten them to get a properly nested list forParametricPlot, like this:

ParametricPlot[Flatten[xpos, ypos],t,0,7]

You can use PlotRange to set the plot limits of the ParametricPlotif you like.

Once you have your plot for the trajectory in air, overlay the trajectorythat the ball would have experienced without air drag on the sameplot. Estimate the difference in range caused by air friction.

(b) Power hitters say they would rather play in Coors Field in Denver thanin sea-level stadiums because it is so much easier to hit home runs.Do they know what they are talking about? To find out, repeat part (a),but instead of overlaying the no air friction plot, overlay the trajectoryof a ball hit in Denver and see if the ball goes significantly farther. Thedensity of air in Denver is about 15% lower than it is at sea level.

Page 10: computational physics 330 - Physics and Astronomy - Brigham

4 Computational Physics 330

(c) Set your initial speed to 47 m/s (105 mph) and vary the angle to findthe maximum range you can get from your sea-level model.

Physicists studying baseball say that backspin (which makes the ballfloat by deflecting air downward through the Bernoulli effect) is essen-tial for record hits. One expert says that an initial speed of 47 m/s withoptimal backspin gives a range of about 122 m (400 feet). Comparethis value to the range you found with Mathematica (which doesn’tinclude backspin). The amount you fell short shows the importanceof backspin.

(d) Finally, to really see that the trajectory is not a parabola, use a verylarge initial velocity and observe that the ball finally comes downalmost vertically. Explain why this is so by contrasting the x and yforces felt by the ball during flight.

Introduction to Matlab

At this point, we will begin to transition from Mathematica to Matlab for ourstudy of numerical computational techniques. Most physicists utilize a variety ofcomputational tools, including packages such as Matlab, Mathematica, Maple,Python, Fortran, Labview, variants of c, and many others. Matlab’s programminglanguage is more typical of the general syntax used in computational physics thanMathematica, so it provides a good compliment to your Mathematica skills. Ifyou learn it well, much of that knowledge will transfer over to other tools.

We’ll start off by learning some of the general syntax of Matlab. As we becomemore skilled, we’ll use it to introduce you to a variety of numerical techniques forsolving physics problems.

P1.6 Read and work through Introduction to Matlab, Chapter 1. Type and executeall of the material written in this kind of font.

(a) Execute the following command at the Matlab command prompt

tic;sum(1:1e7);toc

to measure the time it takes Matlab to allocate an array of integersfrom 1 to 10,000,000 and then sum them. Then execute the analogouscommand in Mathematica

AbsoluteTiming[Total[Table[n, n, 1, 10^7, 1]]]

to see how the two platforms compare in speed.3

(b) Define the Matlab matrices

3If you are careful about what data types and operations you let Mathematica use, you canusually make Mathematica perform the same speed as Matlab. (I.e., Mathematica can countnumbers just as fast as Matlab can since they are using the same CPU.) But by default, Mathematicais often slower because it works hard to keep everything as general as possible.

Page 11: computational physics 330 - Physics and Astronomy - Brigham

Lab 1 Differential Equations and Baseball 5

A=[1,2,3;4,5,6;7,8,9]

and

B=[1,4,5;9,6,3;2,3,1]

Also define the row vector

v1=[1,1,2]

and the column vector

v2=[0.40824829 ; -0.81649658 ; 0.40824829]

Then perform the following operations:

(i) Use both * and .* to multiply A and B. Explain the difference.

(ii) Perform the operation A./B and explain the result.

(iii) Perform the operations A*v1, v1*A, and A*v2 and explain theresults.

Page 12: computational physics 330 - Physics and Astronomy - Brigham
Page 13: computational physics 330 - Physics and Astronomy - Brigham

Lab 2

Qualitative Analysis and Matlab

By this stage in your physics career, you’ve probably grown attached to a com-puter system with symbolic and numeric capabilities. These systems are won-derful tools for solving physics problems and saving you from algebra swamps.However, in some ways handing a physics student a symbolic computationalpackage early in the learning process can be as damaging as handing an elemen-tary school student a calculator as they begin to learn arithmetic. True, it can saveyou some work, but you still need to develop understanding and intuition of thetechniques independent of a computer program to be successful in the long term.

In this lab we start with some exercises to help develop your intuition forunderstanding what differential equations mean. Without this intuition you won’tbe able to propose and refine mathematical models for physical processes, andthe many differential equations you’ll encounter in your physics courses willappear mysterious to you.

How does a differential equation make a curve?

Let’s look at a simple differential equation and try to translate it into words:

d

d ty = y (2.1)

Since dd t y is the slope of the function y(t) this equation says that the bigger y

gets the bigger its slope gets. Let’s consider the two possible cases for initialconditions.

Case 1: y(0) > 0

The differential equation then says that the slope is positive, so y is increas-ing. But if y increases its slope increases, making y increase more, makingits slope increase more, etc. So the solution of this equation is a functionlike e t that gets huge as t increases.

Case 2: y(0) < 0

Now the differential equation says that the slope is negative, so y will haveto decrease, i.e., become more negative than it was at t = 0. But if y is morenegative then the slope is more negative, making y even more negative, etc.Now the solution is a strongly decreasing function like −e t .

7

Page 14: computational physics 330 - Physics and Astronomy - Brigham

8 Computational Physics 330

Let’s consider another example. Suppose that you have discovered someprocess in which the rate of growth of the quantity y is not proportional to y itself,as in exponential growth, but is instead proportional to some power of y ,

d

d ty = y p (2.2)

This idea is referred to as “explosive growth." Keeping in mind that with p = 1we get the exponential function, this equation says that if y starts out positive,y should increase even more than it did before, i.e., get bigger faster than theexponential function. That would have to be pretty impressive, and it is—y goesto infinity before t gets to infinity.

P2.1 Use Mathematica to solve Eq. (2.2) for p = 2 and p = 3 with the initialcondition y(0) = 1. Then plot the solution over a big enough time intervalthat you can see the explosion.

You can play this qualitative analysis game with second-order differentialequations too. Let’s translate the simple harmonic oscillator equation

d 2

d t 2 y =−y (2.3)

into words. We need to remember that the second derivative means the curvatureof the function: a positive second derivative means that the function curveslike the smiley face of someone who is always positive, while negative curvaturemeans that it curves like a frowny face. And if the second derivative is large inmagnitude then the smile or frown is very narrow, like a piece of string suspendedbetween its two ends from fingers held close together. If the second derivative issmall in magnitude it is like taking the same piece of string and stretching yourarms apart to make a wide smile or frown.

Ok, what does Eq. (2.3) say if y = 1 and y ′ = 0 to start? The first derivative iszero, so y(t ) comes out flat, and the second derivative is negative, so the functioncurves downward, making y smaller, which makes the frowniness smaller, butstill negative, so y keeps curving downward until it crosses y = 0. Then with ynegative the differential equation says that the curvature is positive, making ystart to smile and curve upward. It doesn’t curve much at first because y is prettysmall in magnitude, but eventually y will have a large enough negative valuethat y(t) turns into a full-fledged smile, stops going negative, and heads backup toward y = 0 again. When it gets there y becomes positive, the function getsfrowny and turns back around toward y = 0, etc. So the solution of this equationis an oscillation, cos(t ) or sin(t ).

P2.2 For each of the following cases, use qualitative analysis to sketch the solu-tion of the equation on paper. Don’t peek at the answer by having Mathe-matica solve them first.

Page 15: computational physics 330 - Physics and Astronomy - Brigham

Lab 2 Qualitative Analysis and Matlab 9

(a)d

d ty = y2 with y(0) =−1

(b)d 2

d t 2 y = y with y(0) = 1 andd

d ty(0) = 0

(c)d 2

d t 2 y =−y2 with y(0) = 1 andd

d ty(0) = 0

(d)d 2

d t 2 y =−y3 with y(0) = 1 andd

d ty(0) = 0

P2.3 After making all of your sketches in P2.2, check your answer by plotting thesolutions for each equation using Mathematica. The solutions for (c) and(d) will need to be found numerically.

Matlab Scripting Basics

P2.4 Read and work through Introduction to Matlab, Chapters 2-3. Type andexecute all of the material written in this kind of font.

P2.5 Write a Matlab script that asks the user to enter a value for x and printsthe values of sinh x, cosh x, and tanh x, all three properly labeled and onthe same output line. Display 7 decimal places in scientific notation, i.e.,3.1415927e+00.

P2.6 Write a Matlab script that first clears the workspace, then defines the matri-ces A and B as follow

A = 3 8 17

23 10 52 13 5

and B = 19 8 2

10 31 2517 16 29

and then perform the calculations c=A*B, d=A.*B, e=A/B, f=A\B, and g=A./B.Explain the difference between each of these operations to your lab partner.Now add comments before each calculation explaining what they do. Fi-nally, step through your code and watch the values in the result variableschange.

P2.7 Read and work through Introduction to Matlab, Chapter 4. Type and executeall of the material written in this kind of font.

Page 16: computational physics 330 - Physics and Astronomy - Brigham

10 Computational Physics 330

Loops, Logic, and Plotting

P2.8 Read and work through Introduction to Matlab, Chapters 4-5. Type andexecute all of the material written in this kind of font. Then completethe following exercises.

(a) Make a graph of the Bessel function J0(x) from x = 0 to x = 50. Labelthe axes and give the plot a title. Then overlay on the same frame aplot of J1(x) and add a legend to the plot that identifies each curve.You will need to use help legend to learn how to do this.

(b) Write a loop that calculates the first 20 terms of the recursion relation

a1 = 1 ; an+1 =(

n

(n −1/2)(n +1/2)

)an .

and stores each value in an array a. Use Matlab’s debugging com-mands to step through every line of your code while you watch thevalues change in the workspace window.

Plot the a array with semilogy and overlay plots of e−n and 1/n! andlabel each line with a legend. Which function matches the way theterms fall off with n?

(c) Define an array of x-values in the range 0 to 5 with a step size of 0.01.Then make an array f the same size as array x using the zeros com-mand, and use loop and logic commands to load f with the values:

f (x) =

ex , 0 ≤ x < 1e ×cos(x −1) , 1 ≤ x ≤ 5

, (2.4)

Plot f (x) vs. x and label your axes.

HINT: For this problem do not use a command like

if x < 1

because x is an array. You will need to address individual elements ofthe arrays inside your loop.

Page 17: computational physics 330 - Physics and Astronomy - Brigham

Lab 3

Phase Space

Loops and Logic Review

Loops and logic take a while to master. Before moving on to more Matlab, let’stake a minute to review and practice your loops and logic skills.

P3.1 Write a Matlab script that defines the following array

A=[14,42,91,79,95,65,3,84,93,67,75,74,39,65,17]

and then performs a “bubble sort" to order the array elements in A fromsmallest to largest. A bubble sort is a simple sorting algorithm that works

t The bubble sort is not an ef-ficient way to sort. Matlab’ssort command is much bet-ter, but we are learning howto program here.

by repeatedly looping through the array using a for loop, comparing eachpair of adjacent items and swapping them if they are in the wrong order.The for is nested inside a while that repeats until no swaps are needed inthe for loop. The algorithm gets its name from the way smaller elements“bubble” to the top of the list. Step through your code using the debuggingcommands while watching the values in A to make sure it is doing what youthink it should.

Surface and Flow Plots

As we saw in the last lab, you can often visualize the solution of a second-orderdifferential equation without actually solving it. In addition to the qualitativeanalysis that you practiced in the last lab, you can also use phase space1 techniquesto understand how an ODE behaves before grinding it through a numerical ODEsolver to a get solution. In classical mechanics you will learn to call the two-dimensional plane defined by the variables q and p = ∂L

∂q phase space (L is theLagrangian). But for simplicity, in this lab we will use the position x and velocityv as the phase space variables. Before we can explore phase space properly, weneed to learn a few more techniques for plotting functions.

P3.2 Read and work through Introduction to Matlab, Chapter 6. Type and executeall of the material written in this kind of font. Then do the followingexercises:

1R. Baierlein, Newtonian Dynamics (McGraw Hill, New York, 1983), p. 51-54, 140-144, and G.Fowles and G. Cassiday, Analytical Mechanics (Saunders, Fort Worth, 1999), p. 93-98.

11

Page 18: computational physics 330 - Physics and Astronomy - Brigham

12 Computational Physics 330

(a) Write a script that makes a Matlab surface plot of the “mountainfunction" that appears on the cover of Introduction to Matlab forPhysics Students:

f (x, y) = e−|x−sin y |(1+ 1

5cos(x/2)

)(1+ 4

3+10y2

). (3.1)

Plot it from -5 to 5 in x and from -6 to 6 in y and label the x and y axes.Make sure the labels correspond to the correct axes.

105

0.1 n

m

−2

+1+1

Figure 3.1 A simplified model of awater molecule.

(b) Write a script that makes a two-dimensional quiver plot of the electricfield around the “ball and stick” model of a water molecule shownin Fig. 3.1. As a reminder, the electric field E at a point R due to acollection of point particles located at points ri is

E(r) =∑i

1

4πε0

qi

|r− ri |3(r− ri )

Place the oxygen atom at the origin, but choose your grid so it doesn’thave a grid point right at the origin. Otherwise, you’ll have to dealwith a division by zero problem. For the purposes of this problem, youcan use system of units where e/4πε0 = 1 and work in length units ofnanometers.

(c) In a certain region of the atmosphere, the wind is blowing with velocitythat is constant in time, but varies spatially according to

d x

d t= vx = 0.2x2 +0.5y2 +20

d y

d t= vy =−0.1y3 +0.5x2 −10

(3.2)

Write a script that makes a quiver plot of the wind velocity over theregion -10 to 10 for x and y . Now add some stream lines beginning onthe left edge of your plot using the streamline command as shown inFig. 3.2.

Figure 3.2 Streamlines and windvelocity for the a wind velocityfield.

The plot you created in this last exercise is referred to as a flow plot. The arrowsthat you produced with the quiver command show the magnitude and the di-rection of the velocity at each point, and the streamlines show the path that aparticle would follow in this velocity field.

Now let’s see how to apply these graphical tools to understand differentialequations.

Phase Space

Remember from Lab 1 that a second order differential equation can always beseparated into a set of first-order equations by defining an intermediate vari-able. For instance, a one-dimensional projectile with the constant acceleration is

Page 19: computational physics 330 - Physics and Astronomy - Brigham

Lab 3 Phase Space 13

described by the differential equation

d 2x

d t 2 =−g (3.3)

By defining an intermediate variable v , this second-order differential equationcan be written as a system of first-order differential equations like this:

d x

d t= v and

d v

d t=−g (3.4)

Notice that the position and velocity coordinates in Eq. (3.4) have the same formas the flow velocities in Eq. (3.2), i.e. the first derivatives on the left equal expres-sions on the right with no derivatives. If you think of d x/d t and d v/d t in Eq. (3.4)as flow velocities in the x-v plane, the right-hand sides of these equations tellus what the “flow” velocity is at each point in space. At any point in time t , thecoordinate [x(t ), v(t )] gives the phase-space point that represents the “state” ofthe system. Given an initial starting point, we can then trace out a curve calleda phase space trajectory analogous to the streamlines we plotted in the previoussection.

Part of the power of phase space flow plots is that we don’t have to solve thedifferential equation to make the flow plot. We just evaluate the right-hand sidesof Eq. (3.4), for example, and draw arrows at each point in the (x, v) space thatindicate which way the solution at that point will move if we take a small step intime. To draw the phase space trajectories, we just connect up the arrows overshort time intervals. In this way we can explore the behavior of the system for awide range of initial conditions without ever actually solving the ODE for any ofthese conditions. Not too shabby! Let’s practice.

P3.3 Sketch a phase space diagram for the one-dimensional projectile in Eq. (3.4)by hand on paper. Then draw some phase-space trajectories for a ball beingthrown up with various velocities. After you have done your work by hand,check it by using Matlab with the quiver and streameline tools.

P3.4 Now let’s throw a ball really hard (with no atmosphere) so that its accelera-tion is no longer constant, but governed by Newton’s law of gravity instead:

d 2x

d t=−G

ME

(x +RE )2

Here ME = 6×1024 kg is the mass of the earth, RE = 6.4×106 m is the radiusof the earth, and G = 6.67×10−11 m3 kg−1 s−2 is the universal gravitationalconstant. Write this equation as a system of first-order equations. Thenmake a quiver plot and overlay phase-space trajectories for the followingsituations:

(a) You throw the ball up at human speeds of 1 m/s, 10 m/s, and 40 m/s.

Page 20: computational physics 330 - Physics and Astronomy - Brigham

14 Computational Physics 330

(b) You throw the ball up with a Saturn V rocket, and achieve speeds of1,000 m/s, 5,000 m/s, and 10,000 m/s.

Hint: You will need to choose reasonable limits for your flow plot, and theywill be different for (a) and (b).

Page 21: computational physics 330 - Physics and Astronomy - Brigham

Lab 4

Calculus and a Bouncing Ball

For the past couple of labs we’ve focused on ways to visualize the solutions todifferential equations using qualitative analysis and flow plots. In this lab we’llbegin to learn how to solve differential equations numerically to get numbers andplots. The numerical technique that we use to do this is to represent functionsof space and time using discrete grids rather than continuous variables. Thenwe approximate derivatives as finite differences on this discrete grid rather thanthe infinitesimally small differences that we use in analytic calculus. We begin bytalking about how to work with grids in Matlab and how to do calculus on them.Then we’ll use these ideas to develop a crude technique for numerically solvingthe differential equations for a bouncing ball.

Calculus on a Discrete Grid

P4.1 Read and work through Introduction to Matlab, Chapter 7. Type and executeall of the material written in this kind of font. Then complete thefollowing exercises.

(a) Use the simple mid-point rule to numerically do the integral∫ 2

0x2e−x cos xd x . (4.1)

Experiment with different values of N until you are confident that youhave the answer correct to 6 decimal places. Then verify that you didit right by doing the same integral using Matlab’s integral commandusing an anonymous function and passing it into integral.

(b) Consider the simple function f (x) = ex . Evaluate f ′(x) at x = 1 usingboth the forward and centered difference approximation to the firstderivative. Write a loop that decreases h from 1 to 10−20 by dividingsuccessively by 2 and calculate the error of the two derivative formulas(i.e., abs(fp/exp(1)-1)where fp is the numerical derivative) at eachh. Make a loglog plot of the errors vs. h. Show that the centereddifference formula works better, but that both formulas are bad forvery small values of h.

Explain why very small values of h make the approximate derivativebe wrong, giving zero instead of a good approximation to f ′. Thesection below on roundoff will be helpful.

15

Page 22: computational physics 330 - Physics and Astronomy - Brigham

16 Computational Physics 330

Roundoff

The effect illustrated in exercise 4.1(b) is called roundoff and it rears its ugly headevery time you subtract two numbers on a computer. To understand round-off, consider the following two 15-digit numbers: a = 1.2345678912345 andb = 1.2345678918977. These are impressively accurate numbers, but their differ-ence is not so impressive: b−a = .0000000006632. Where did all of the significantdigits go; we started with 15 and now we only have 4? The problem is that thenumbers were so close together that subtraction made most of the significantfigures go away. When you work with numerical data on a computer you onlyhave a finite number of significant digits (15 in Matlab), so you have to be carefulwhen you subtract. And because subtraction is the key idea in differentiating, wehave to be careful about how we choose our step size h. As you can see in thisexercise, making it very small makes things worse, not better.

Solving Differential Equations Numerically

Now that we understand the basics of taking derivatives on a grid, let’s look at howto numerically solve differential equations. Consider the motion of a projectilenear the surface of the earth with no air resistance. The differential equationsthat describe the projectile are

d x

d t= vx

d y

d t= vy

d vx

d t= 0

d vy

d t=−g

(4.2)

along with some initial conditions, x(0), y(0), vx (0), and vy (0). This set of equa-tions is easily solved analytically, but imagine that we didn’t have an analyticsolution. How could we numerically model the motion of the projectile?

The basic idea in a numerical solution for a system like this is to think of timeas being a discrete grid rather than a continuous quantity. It is easiest to havean evenly spaced time grid [t0, t1, t2, ...] with t0 = 0, t1 = τ, t2 = 2τ, etc. We labelthe variables on this time grid using the notation x0 ≡ x(0), x1 ≡ x(τ), x2 ≡ x(2τ),etc. With this notation, we can write the equations in (4.2) using the (inaccurate)forward difference approximation of the derivative that you learned about in thereading:

xn+1 −xn

τ= vx,n

yn+1 − yn

τ= vy,n

vx,n+1 − vx,n

τ= 0

vy,n+1 − vy,n

τ=−g

(4.3)

Notice that the left sides of these equations are centered on the time tn+1/2, butthe right sides are centered at time tn . This makes this approach inaccurate, butif we make τ small enough it can work well enough to see the principles involved.

Page 23: computational physics 330 - Physics and Astronomy - Brigham

Lab 4 Calculus and a Bouncing Ball 17

By solving the equations in (4.3) we can obtain a simple algorithm for steppingour solution forward in time:

xn+1 = xn + vx,nτ yn+1 = yn + vy,nτ

vx,n+1 = vx,n vy,n+1 = vy,n − gτ(4.4)

This method of approximating solutions is called Euler’s method. In general, it’st The name Euler does not

rhyme with “cooler”; itrhymes with “boiler”. Youwill impress your fellow stu-dents and your professorsif you give this importantname from the history ofmathematics its properpronunciation.

not very good, especially over many time steps. However, it provides a foundationfor learning other better methods.

P4.2 Make a program in Matlab to model the motion of a ball bouncing on thefloor using Euler’s method. In your script, define the initial position of theball with x=0 and y=1, and the initial velocity with vx=1 and vy=0. Thenwrite a while loop to step the position and velocity forward in time usingEq. (4.4). Have your while loop exit when x > 10. Just store the new valuesover the top of the old ones in the loop, like this

x=x+vx*tau;

HINT: When you code the y equations, the order of assignment matters.Think about which y equation should come first.

(a) To simulate bouncing, put an if statement in your loop that checks ify is less than zero. When it is, make vy positive like this

vy=abs(vy)

Make a movie by plotting the position of the ball as a dot each timethe loop iterates, like this:

plot(x,y,'.')

axis([0 10 0 1.5])

pause(0.001)

(b) Our bouncing condition in part (a) is lousy. Make it better by addingsome more logic that does the following:

(i) Test to see if y will go less than zero on this time step, but don’tactually change y yet.

(ii) If y won’t go less than zero this step, just do a regular Euler step.

(iii) If it will go negative this time step, determine a smaller time stepτ1 such that an Euler step will take the ball to y = 0. Then take anEuler step with τ1. After taking this small step, make the y-velocitypositive as before

vy=abs(vy)

and then take an Euler step of τ2 = τ−τ1 to finish off the time interval.

Play with different values of τ and notice that even with this improvedbouncing condition, Euler’s method is always unstable (i.e. the ampli-tude of the bounce continues to grow). This is a limitation of Euler’smethod, and we’ll develop better methods to overcome this shortcom-ing next time.

Page 24: computational physics 330 - Physics and Astronomy - Brigham

18 Computational Physics 330

(c) Make your model look more realistic by adding some loss to the codethat represents the bounce process, like this

vy=0.95*abs(vy)

This damping will mask the growth of Euler’s method for a suitablysmall τ.

Page 25: computational physics 330 - Physics and Astronomy - Brigham

Lab 5

Matlab’s ODE Solvers and Meteorites

In the previous lab, we learned a crude method for numerically solving dif-ferential equations called Euler’s method. In this lab we learn how to take thenext step in refining that rudimentary technique into a more accurate ODE solver.After we have a good idea how ODE solvers are built and refined, we will introduceyou to some powerful differential equation solvers built into Matlab. Before wecan understand how to use these differential equation solvers, we need to learnhow Matlab handles functions.

Functions in Matlab

To this point, we’ve mostly relied on Matlab’s built-in functions tied together withsome code to perform our work. As our numerical techniques advance, we’ll needto be able to write our own functions. Pay close attention to this material, becauseit will be important throughout the remainder of the course.

P5.1 Read and work through Introduction to Matlab, Chapter 8. Type and executeall of the material written in this kind of font. Then do the followingexercises:

(a) Write an M-file function called InvSum.m that contains a loop toperform the sum

S(N ) =N∑

n=1

1

n

Your function should take N as an input and return the sum as its out-put. Write a separate script that contains a loop that loads a variable Swith S(N ) from N = 1 to N = 1,000. Plot the array S and note that thesum diverges as N gets bigger, but only weakly.

(b) Write another function called EulerSum.m that computes the quantity

Se (N ) =(

N∑n=1

1

n

)− ln(N )

Write a separate script that contains a loop that loads a variable Se

with Se (N ) from N = 1 to N = 1,000. Show that as N becomes large Se

approaches a limit. This limit is called Euler’s constant, often repre-sented by the Greek letter γ. To 15 digits, Euler’s constant is

γ= 0.577215664901532

19

Page 26: computational physics 330 - Physics and Astronomy - Brigham

20 Computational Physics 330

Add a second output to EulerSum.m that returns the error |Se (N )−γ|. Make a 2-panel subplot that plots Se in the upper pane and asemilogy plot of the error in the lower pane.

(c) A square wave can be approximated by a sum of sine waves accordingto

f (x) =N∑

n=1,3,5,...an(x) (5.1)

where

an = 4

nπsin

(nπx

L

)(5.2)

Make an anonymous function that evaluates an(x) and then write aloop that evaluates f (x) for a given value of N . Use L = 1 and plotf (x) from -5 to 5. Notice that your function will need to accept twoarguments: n and x. Use your code to explore how big N needs to beto get a good approximation to a square wave.

Numerically Solving Differential Equations

In the previous lab you learned how to numerically solve a differential equationusing a technique called Euler’s method. As you’ll recall, it wasn’t a very accuratemethod. Today we will review Euler’s method, and then build on it to find a bettertechnique

P5.2 Read and work through Introduction to Matlab, Sections 9.1-9.2. Type andexecute all of the material written in this kind of font. Then work thefollowing problems.

(a) Let’s start simple by modeling an object dropped from rest 10 kmabove the ground, neglecting air resistance. This is still not highenough to worry much about the full gravitational force, so still useF = mg for the gravitational force. On a piece of paper, write downNewton’s second law for this system and then convert it to a first orderset of coupled equations. Write the derivatives as finite differenceson a grid in time like we did in the last lab, and solve the resultingequations to derive the equations for Euler’s method. (Don’t peek atthe answer, derive Euler’s method again from scratch.)

(b) Implement your equations from part (a) in a Matlab script to plot y(t )until your object hits the ground. Compare your numerical solutionwith the exact solution for various values of τ.

(c) Modify your code from part (b) to use second-order Runge-Kutta.Evaluate how your accuracy changes as you vary τ, and compare withEuler’s method.

Page 27: computational physics 330 - Physics and Astronomy - Brigham

Lab 5 Matlab’s ODE Solvers and Meteorites 21

(d) Read and work through Introduction to Matlab, Sections 9.3. Alsoglance through Section 9.4, but we won’t be using it today. Then useMatlab’s numerical differential equation solver ode45 to solve themotion of the particle by writing a rhs function.

Important: As you worked through this material in Introduction toMatlab, you learned how to use an M-file named rhs.m to solve dif-ferential equations. As you do this problem and in later labs, pleasedon’t keep using the name rhs.m over and over. Invent a uniquename, like rhs5_2.m, and change the call to ode45 to correspond:ode45(@rhs5_2,...). This will make it possible for you to comeback later and see how you did each of the problems.

(e) Make another version of your code from part (d) that uses an anony-mous function instead of an external m-file rhs function. In subse-quent problems and labs, you are free to use either syntax, but whenthe functions get complicated its usually easier to use the external rhsfunction.

P5.3 Use Matlab’s ode45 to numerically solve the following equations. Plot thenumerical solutions from x = 0 to x = 10 and overlay plots of the analyticsolutions. Fiddle RelTol and get a feel for how the accuracy changes withthis parameter.

(a)d y

d t= (t 2 − y2)sin y ; y(0) =−1 (5.3)

(b) Bessel’s Equation with f (0) = 0, f ′(0) = 1, and n = 1

x2(

d 2

d x2 f (x)

)+x

(d

d xf (x)

)+ (x2 −n2) f (x) = 0 (5.4)

When you write this as a first order set of equations, you will find thatthere is a singularity at x = 0. Since you may periodically encounterthis situation, let’s think about how to handle singularities. You can’tuse x = 0 as your starting point for the ODE solver, but rather you’llneed to use something small like x = 0.0001. But then the initialconditions given above are are wrong. We need to find an approximatesolution to the differential equation near the singularity so we cancalculate correct initial conditions.

In general, the process is to assume the solution can be expandedaround the singular point x0 like this

f (x) ≈ a0 +a1(x −x0)+a2(x −x0)2 +·· · (5.5)

and then solve for the coefficients. Our case is fairly simple, and weonly need a solution that is good enough to estimate the functionvalue and the first derivative very near x = 0. So approximate the

Page 28: computational physics 330 - Physics and Astronomy - Brigham

22 Computational Physics 330

solution as f (x) = a0+a1x and its derivative along with the two initialconditions to find values for a0 and a1. Then use your approximatesolution to get your new initial conditions f (0.0001) and f ′(0.0001),and you are off and running.

P5.4 A meteorite enter earth’s atmosphere at 15,000 m/s and begins experienc-ing air resistance and vaporizing. We’ll model this meteorite like we didbaseballs back in Lab 1, except the air density and the mass of the projectilewill vary as it travels. Recall that the equation of motion with air resistanceis

r = Fdrag

m− g y

where

Fdrag =−1

2Cdρ(y)πa2|v|v

(a) Write a Matlab script to model the meteorite’s motion. Start the me-teorite at an elevation of 50 km and assume that it comes straightdown so we only have to worry about the y-component of its motion.Assume that it is a sphere of radius a = 0.1 m, made mostly of ironso its density is ρm = 7 g/cm3, and has a coefficient of drag Cd = 0.35.For this part, have the atmosphere “turn on” suddenly at 44 km at auniform density of 1 kg/m3. Make plots of the meteorite’s positionand velocity versus time until it arrives at the earth.

(b) Once you have part (a) working well, switch the atmospheric den-sity so that it is still zero above 44 km, but below 44 km the densitygradually increases according to

ρ(y) = M

R(T0 −Ly)p0

(1− Ly

T0

) g MRL

wherep0 = 1×105 Pa

T0 = 288 K

g = 9.8 m/s2

L = 0.0065 K/m

R = 8.3 Jmol−1K−1

M = 0.03 kg/mol

(c) Plot the meteor’s total mechanical energy E = mg y + 12 mv2 as a func-

tion of y . Notice that the mechanical energy is not conserved, butdecreases as energy goes to heating up the meteor and the surround-ing air.

P5.5 (Optional) Now let the meteor’s mass decrease as it melts. Calculate theinitial mechanical energy of the meteor and store it in a global variable.

Page 29: computational physics 330 - Physics and Astronomy - Brigham

Lab 5 Matlab’s ODE Solvers and Meteorites 23

In your rhs function, calculate how much energy has bee lost at the givenconditions. Then assume that 20% of the lost mechanical energy goesto melting the meteor, while the rest goes to warming the surroundingair. Further assume that it takes Cm = 200 kJ/kg to remove mass from themeteor and that it remains a sphere as it melts, but don’t let the meteor’smass ever go below 1 gram so that you don’t have division by zero troubles.Plot the meteor’s mass as a function of height and see how far into theatmosphere it gets before it is entirely gone. Then play with various initialmeteor sizes to see how big it needs to be to reach the surface of the earthwith an appreciable mass.

Hint: If E0 is your initial energy, the change in energy as the meteor falls is

∆E = E0 −(mg y + 1

2mv2

)(5.6)

where m is your current (unknown) mass. Your current mass is related tothe change in energy via

∆E = Cm(m0 −m)

0.2(5.7)

where m0 is the meteor’s initial mass. Combining Eqs. (5.6) and (5.7), wefind that the current mass in terms of the current values of the position andvelocity is given by:

m = Cmm0/0.2−E0

Cm/0.2− g y − 12 v2

. (5.8)

To find the current size of the meteor, note that the mass is related to radiusvia

m = 4

3πa3ρm (5.9)

so the radius for given conditions is related to the current mass via

a =(

3m

4πρm

) 13

. (5.10)

Page 30: computational physics 330 - Physics and Astronomy - Brigham
Page 31: computational physics 330 - Physics and Astronomy - Brigham

Lab 6

The Harmonic Oscillator and Resonance

The harmonic oscillator is probably the most studied system in dynamics. Inthis lab we use several of the numerical tools that we have developed to exploresome of the behavior of this system.1 Before we dive into the computationaldetails, let’s remind ourselves of the basic physics of a harmonic oscillator.

The Basic Oscillator

The basic oscillator equation is given by

d 2

d t 2 y(t ) =−ω20 y(t ). (6.1)

The solutions to this equation are just sines and cosines that wiggle forever intime at the natural frequency ω0:

y(t ) = A sin(ω0t )+B cos(ω0t ) (6.2)

Of course, no real oscillator wiggles forever. To model a real system we need toadd damping.

The Damped Oscillator

If we add some linear damping to the system, the harmonic oscillator equationbecomes

d 2

d t 2 y(t ) =−ω20 y(t )−2γ

d

d ty(t ), (6.3)

where the damping factor γ describes the amount of damping—a large γ meansthat there is a lot of damping. If you ask Mathematica to solve Eq. (6.3), it will tellyou that the solution is

y(t ) = Ae−t

(γ+pγ2−ω2

0

)+Be

−t(γ−pγ2−ω2

0

)(6.4)

Equation (6.4) looks impressive, but if it’s supposed to be an oscillator that damps,where are the sines and cosines? The problem is that we haven’t specified howbig ω0 and γ are yet. Let’s think physically for a minute.

1You can read more about the simple harmonic oscillator in the following references: R. Baierlein,Newtonian Dynamics (McGraw Hill, New York, 1983), Chap. 2, and G. Fowles and G. Cassiday,Analytical Mechanics (Saunders, Fort Worth, 1999), Chap. 3.

25

Page 32: computational physics 330 - Physics and Astronomy - Brigham

26 Computational Physics 330

Suppose that you put a pendulum in motor oil at 50 degrees below zero. Thisis an oscillator with a big γ. If you pull the pendulum back and release it, youare not going to see any swinging; the pendulum will just slowly ooze back tothe vertical position and stay there. We refer to this system as being overdamped.Look at Eq. (6.4) and convince your lab partner that this solution is made up ofdecaying exponentials when γ is big (specifically γ>ω0).

Now imagine what would happen if we decrease the damping, say by warmingthe oil up, or using WD-40 instead, or maybe even just air. In this case, thependulum will swing back and forth, but the amplitude will decrease over time.But by what miracle did the exponential functions in the original solution becomesines and cosines? To see, let’s work through the algebra explicitly:

P6.1 (a) Assume that the argument of the square root in Eq. (6.4) is negative.Then using paper and pencil factor out the imaginary number (i =p−1) from the square root and show that Eq. (6.4) can be written as

y(t ) = e−tγ[

Ae−iωd t +Be iωd t]

(when γ<ω0) (6.5)

where the frequency at which the damped oscillator “wants" to wiggleis given by

ωd =ω0

√1−γ2/ω2

0 (6.6)

Then, still using paper and pencil, use Euler’s formula e iθ = cos(θ)+i sin(θ) to write Eq. (6.5) as an exponential decay multiplying somesinusoids.

(b) You will have some imaginary numbers in your solution, which isbothersome since we expect the displacement y(t ) to be a real number.But we still haven’t chosen initial conditions. But if we choose realvalues for y0 and v0, it will force our solution to be real. To see this,code your final equation from (a) into Mathematica as a function(i.e. y[t_] := Exp[-tγ] etc.) and then create a velocity functionas a derivative of position like this: v[t_] := y'[t]. Now find twoalgebra equations by setting the position and velocity at t = 0 equalto the real constants y0 and v0. Solve these equations to find A andB . Finally, use a replacement rule to substitute these values for Aand B back into your equation for y(t ) and show that the equation iscompletely real.

(c) Examine the equations above and describe how the decay rate andthe oscillation frequency change as damping is increased.

To recap, a negative argument in the square-root√γ2 −ω2

0 gives rise to theoscillatory terms. If the square root is imaginary (γ<ω0), the exponentials arecomplex (sines and cosines multiplied by a decaying exponential) and we haveoscillation. If the argument of this square root is positive (γ>ω0), then both ofthe fundamental solutions in Eq. (6.4) are decaying exponentials and we only

Page 33: computational physics 330 - Physics and Astronomy - Brigham

Lab 6 The Harmonic Oscillator and Resonance 27

have damping (no wiggles). The transition between the two is when the argumentof the square roots is zero, i.e., when γ = ω0. This special case is called criticaldamping.

Phase Space Analysis

Let’s apply our techniques for analyzing differential equations in phase space tothe harmonic oscillator.

P6.2 (a) Sketch a phase space diagram for a simple harmonic oscillator by handon paper. Draw at least two phase-space curves for initial conditionsx(0) = 1, v(0) = 0 and another for x(0) = 0 and v(0) = 1.

(b) Use Matlab to make a flow plot of x(t ) and v(t ) for a simple harmonicoscillator with ω0 = 2. Now plot three phase space trajectories bynumerically solving the differential equation with initial values x0 = 1and v0 = 0, v0 = 1.4, and v0 = −1 and run them from t = 0 to t = 1.Overlay the three trajectory plots on your flow plot. Identify each of thethree initial conditions on your plot, and explain what the harmonicoscillator does along each trajectory.

(c) Now add linear damping to your model with damping coefficientγ= 0.5:

d x

d t= v ;

d v

d t=−ω2

0x −2γv . (6.7)

Make a flow plot for this model and overlay trajectories with the sameinitial conditions as (b), but run from t = 0 to t = 20. Explain how thearrows show what the solution will do.

Now change the damping coefficient to γ = 4 and explain how theflow plot describes the overdamped system.

(d) Repeat (c), but change your model to include air-damping with γ= 0.5in the following differential equation:

d x

d t= v ;

d v

d t=−ω2

0x −2γv |v | . (6.8)

Explain how this picture looks different from the ones in part (b), andwhy.

Page 34: computational physics 330 - Physics and Astronomy - Brigham

28 Computational Physics 330

The Driven, Damped Oscillator

If we add a sinusoidal driving2 force at a frequency ω to the harmonic oscillator,the equation of motion becomes

d 2

d t 2 y(t ) =−ω20 y(t )−2γ

d

d ty(t )+F0 cos(ωt ) (6.9)

Now we have two frequencies in play—the driving frequency ω and the damped-oscillator frequency ωd given by Eq. (6.6). The typical behavior of the driven-damped harmonic oscillator starting from rest is as follows: an initial period ofstart-up with some beating between the two frequencies (ω and ωd ), then theoscillations at ωd damp out and the system transitions to a state of oscillation atthe driving frequency ω.

It is possible to solve Eq. (6.9) symbolically, but for practice let’s study itsbehavior by solving it numerically.

P6.3 Use Matlab to numerically solve Eq. (6.9) and plot x(t ) from t = 0 to t = 300with ω0 = 1, F0 = 1, ω= 1.1, and γ= 0.01. Start from rest, with y(0) = 0 andy(0) = 0. Note the initial beating between frequencies and verify graphicallythat the final oscillation frequency of y(t ) is ω.

Resonance

When you push someone in a swing, you find that if you drive the system at theright frequency, you can get large amplitude oscillations. This phenomenon is anexample of resonance, and the frequency at which the system has the maximumresponse is called the resonance frequency ωr . If you drive a system at a frequencyfar from ωr you only get small oscillations.

P6.4 Study resonance in the damped-driven oscillator by writing a script thatmakes plots of y(t ) starting from rest and running for a long time so all thebeating has stopped. Use F0 = 1, γ= 0.1 ω0 = 1.

(a) Drive the system at ω= 1. When you have your script running, writesome code that measures the amplitude of the steady-state oscilla-tions using the colon command to select a few cycles of oscillationat the end of the time period and the max command to find the maxi-mum value.

(b) Add a for loop to your script that varies the driving frequency fromω= 0.5 to ω= 1.5. For each driving frequency, find the steady-stateoscillation amplitude A (i.e. the amplitude of oscillation after all the

2For more information about the driven, damped harmonic oscillator, see: R. Baierlein, Newto-nian Dynamics (McGraw Hill, New York, 1983), p. 55-62, and G. Fowles and G. Cassiday, AnalyticalMechanics (Saunders, Fort Worth, 1999), p. 99-106.

Page 35: computational physics 330 - Physics and Astronomy - Brigham

Lab 6 The Harmonic Oscillator and Resonance 29

beating has died out) and plot the steady-state amplitude A versusthe driving frequency ω. Find the peak of this curve, and compare itslocation to ωd for this system.

In this problem you should have observed that the resonance frequency ωr (i.e.the peak of the resonance curve) is not the same as the same as the dampedfrequency ωd . When damping is small, ωr and ωd are close, but they are not thesame.

Resonance Curves

We can study resonance in more detail by making a resonance curve. A resonancecurve plots the steady state oscillation amplitude (after the beating has died away)vs. the driving frequency. You did this by brute force in the last problem, but forthe simple driven-damped equation we can actually find an analytic solution forthe resonance curve. The steady-state oscillation has the form

y(t ) = A cos(ωt −φ) (6.10)

where A is the steady state amplitude, ω is the driving frequency, and φ is thephase difference between the driving force and the oscillator’s response. Let’sderive an expression for A(ω).

P6.5 Our algebra will be easier if we write Eq. (6.10) using complex notation likethis:

y(t ) = Ae i (ωt−φ) (6.11)

The real part of Eq. (6.11) is equivalent to Eq. (6.10) because of Euler’srelation e i x = cos x + i sin x. If we also write the driving force using thiscomplex notation trick, we can find the steady state solution with just alittle algebra.

(a) On paper, substitute the complex steady-state solution in Eq. (6.11)into the driven damped oscillator equation with a complex drivingforce:

d 2

d t 2 y(t ) =−ω20 y(t )−2γ

d

d ty(t )+F0e iωt (6.12)

Carry out the derivatives and cancel the common factor of e iωt . Thenmanipulate the equation so that e iφ appears in only one term on theright side. Replace the complex exponential with trig functions usinge iφ = cosφ+ i sinφ to find the following equation:

−ω2 A+ i 2γωA+ω20 A = F0(cosφ+ i sinφ)

Finally, separate this complex equation into two real equations: onefor the real part and one for the imaginary part.

Page 36: computational physics 330 - Physics and Astronomy - Brigham

30 Computational Physics 330

(b) Divide the two equations found in (a) to find the phase difference φbetween the driving force and the oscillatory response:

tanφ= 2γω

ω20 −ω2

. (6.13)

Now square both equations found in (a), add them together, and solvefor the the steady-state amplitude A to find

A(ω) = F0√(ω2

0 −ω2)2 +4γ2ω2(6.14)

HINT: In solving for A it will be useful to recall that cos2φ+ sin2φ= 1.

(c) The resonance curve A(ω) defined by Eq. (6.14) gives steady state am-plitude of the oscillation as a function of the driving frequency. Writea script that plots of Eq. (6.14) for the parameters in P6.4 and com-pare the plot with your numerical results. Also plot φ(ω). φ(ω) tellsyou the phase difference between the driving force and the oscillatorresponse.

Now make plots for several values of γ and verify that a smaller damp-ing coefficient γ leads to larger and sharper resonance. Show ana-lytically that the peak of the resonance curve is not at the dampedfrequency ωd , but occurs at

ωr =√ω2

d −γ2 =√ω2

0 −2γ2 (6.15)

Page 37: computational physics 330 - Physics and Astronomy - Brigham

Lab 7

The Pendulum

The equation of motion of a simple pendulum is

θ =−ω20 sinθ , (7.1)

where θ is the angle (in radians) between the pendulum and the vertical directionand ω0 is the small-amplitude oscillation frequency. This is a nonlinear equation,so we often use the small angle approximation sinθ ≈ θ to simplify Eq. (7.1) into asimple harmonic oscillator. But it doesn’t take a very large amplitude before thesmall angle approximation falls apart. In this lab, we study the large amplitudebehavior of the pendulum, which can be quite different from the simple harmonicoscillator.

Figure 7.1 A phase space flow plotfor a pendulum.

P7.1 Prove that Eq (7.1) is, in fact, nonlinear by showing that if you have two ofits solutions θ1(t ) and θ2(t ), then their sum θ1(t )+θ2(t ) is not a solution ofthe differential equation. When this happens, we say that the differentialequation is nonlinear. Use pencil and paper; Mathematica will just slowyou down.

P7.2 Use Eq. (7.1) with Matlab to make a phase space diagram with Matlab’squiver command and plot trajectories with Matlab’s streamline com-mand for small oscillations, large oscillations, and motion where the pen-dulum is rotating completely around rather than oscillating back and forth.Make trajectories for both clockwise and counter-clockwise rotations.

Period and Frequency of the Pendulum

Figure 7.2 A simple pendulumcomprised of a massless stick oflength ` with a mass m at the end.

A pendulum is an extended object that is free to rotate with moment of inertia Iabout a pivot point. The distance from the pivot point to the center of mass of theobject is `, and the small-amplitude oscillation frequency is ω0 =

√mg`/I . If the

pendulum is a simple massless stick of length ` with all of the mass at the end ofthe stick, the small-amplitude oscillation frequency simplifies to ω0 =

√g /`.

We can find the large-amplitude oscillation frequency of the pendulum byusing an energy method.1 The kinetic energy of the pendulum is I θ2/2 and thepotential energy is mg`(1−cosθ) (see Fig. 7.2). The total energy of a pendulumcan be found when the pendulum is at the maximum displacement, which wewill denote by θ0. At this point, the center of mass is at a height of `(1−cosθ0)above the equilibrium position and the kinetic energy is zero, so the total energy

1 G. Fowles and G. Cassiday, Analytical Mechanics (Saunders, Fort Worth, 1999), p. 318-320

31

Page 38: computational physics 330 - Physics and Astronomy - Brigham

32 Computational Physics 330

is mg`(1− cosθ0). As the pendulum oscillates, energy shuttles back and forthbetween kinetic and potential according to

1

2I θ2 +mg`(1−cosθ) = mg`(1−cosθ0) (7.2)

The first term on the left is the kinetic energy, the second term is the potentialenergy, and the right side is the total energy of the system.

P7.3 Using paper and pencil, separate the variables θ and t in Eq. (7.2) and showthat it can be written as

ω0d t = dθ√2cosθ−2cosθ0

(7.3)

Figure 7.3 The frequency of a pen-dulum depends on the amplitudeof oscillation. The variation of fre-quency with amplitude is smallestfor low-amplitude oscillations, soits easier to get good accuracy withlong pendulum and small angleoscillations as in a grandfatherclock.

To find the period of oscillation, we integrate both sides of Eq. (7.3) over aquarter period of the motion (from θ = 0 to θ = θ0 on the angle side and fromt = 0 to t = T /4 on the time side), like this

ω0

∫ T /4

0d t = 1p

2

∫ θ0

0

dθ√cosθ−cosθ0

(7.4)

The time integral on the left is simply ω0T /4, but the θ integral on the right isdifficult. After carrying out the time integral and performing some judiciousvariable substitutions and a little algebraic massaging, we can rewrite Eq. (7.4) as

T = 4

ω0

∫ π/2

0

dφ√1− sin2(θ0/2)sin2φ

(7.5)

The φ integral in Eq. (7.5) is not any easier than the θ integral in Eq. (7.4), but ithas come up in enough problems that it has been given a name: the completeelliptic integral of the first kind, called K (m):

K (m) ≡∫ π/2

0

dφ√1−m sin2φ

(7.6)

Matlab and Mathematica know how to evaluate K (m) functions for 0 ≤ m ≤ 1 justlike they can evaluate sines, cosines, and Bessel functions. Thus, we can write theperiod T of the pendulum as

T = 4

ω0K

(sin2(θ0/2)

)(7.7)

Now we can use the relation ω = 2π/T to obtain an expression for the angularfrequency of the pendulum as a function of amplitude θ0.

ω(θ0) = πω0

2K(sin2(θ0/2)

) (7.8)

00

Figure 7.4 Oscillation frequencyas a function of the maximumamplitude θ0.

Note that the natural oscillation frequency ω(θ0) of the pendulum dependson amplitude θ0, as shown in Fig. 7.4. This gives the pendulum some interestingcharacteristics.

Page 39: computational physics 330 - Physics and Astronomy - Brigham

Lab 7 The Pendulum 33

P7.4 Use Matlab to plot ω(θ0) from θ0 = 0 to θ0 = π with ω0 = 1 and explainphysically why it looks like it does. In particular, explain why the frequencygoes to zero at θ0 =π. You’ll need to use the online help to see the syntaxfor evaluating the elliptic integral function.

Now let’s solve the pendulum equation numerically using Matlab.

P7.5 Use Matlab’s numerical differential equation solver ode45 to solve the pen-dulum, again with ω0 = 1 and initial conditions θ(0) = θ0 and ω(0) = 0. Runyour script and plot the solution θ(t ) for the following values of θ0: 0.1, 0.5,1.0, π/2, 0.9π, and 0.98π. For each value overlay a plot of a cosine functionof matching amplitude and with a frequency ω(θ0) from Eq. (7.8). Verifythat Eq. (7.8) gives the correct frequency, but that for large amplitudes thependulum motion is not sinusoidal.

P7.6 Now let’s study what happens when we add driving and damping.

(a) First we’ll review what happens when we drive an undamped har-monic oscillator. Write a Matlab script that solves the driven oscillatorequation

y +ω20 y(t ) = F0 sin(ωt ) (7.9)

and plot the solution y(t ) withω0 =ω= 1. Run for a long enough timethat you can see the amplitude heading off to infinity, even with smallvalues of F0.

(b) Now drive the pendulum with an external torque, like this

θ+ω20 sinθ =αsinωτt . (7.10)

Drive the pendulum at resonance for small amplitudes, with ω0 = 1,ωτ = 1, and α = 0.1. Since it is driven, you can just start it at rest:θ(0) = 0 and θ(0) = 0. Run for a long enough time that you can seethat the pendulum amplitude doesn’t simply go to infinity like theharmonic oscillator. Explain why not.

(c) Finally, add some linear damping (−γθ, γ = 0.1), to the right-handside of Eq. (7.10). Use the same conditions as in (b) and watch howthe motion changes. Explain the damped behavior and explore howit depends on α. Also vary the driving frequency ω in the range0.90ω0 → 1.05ω0 and explain why ω = ω0 doesn’t give the largestamplitude.

Linear Algebra

P7.7 Read and execute the examples in Introduction to Matlab, Chapter 10. Thencomplete the following exercises.

Page 40: computational physics 330 - Physics and Astronomy - Brigham

34 Computational Physics 330

(a) Use Matlab’s dot command to find the angle between the vectorsA = [1,2,3] and B = [−3,2,1].

HINT: You will need to calculate the magnitude of a vector to do thisproblem.

(b) Use Matlab’s cross command to find the angular momentum L =mr×v of a particle at r = [1,2,3] with velocity v = [6,3,1] and massm = 2.3.

Curve Fitting

P7.8 Read and execute the examples in Introduction to Matlab, Chapter 11. Thencomplete the following exercises.

Figure 7.5 This third-order fit isnot very good; you will do better.

(a) Use polyfit to find a fourth-order polynomial approximation to thefunction f (x) = e−x J1(x) on the interval x ∈ [0,3]. (This function and amediocre third-order fit are shown in Fig. 7.5). Plot both f (x) and thepolynomial fit together on the same graph using different colors. Thenplot the polynomial as a dashed line instead of a solid one. Finally,change the polynomial order to 6 and see if the fit improves.

(b) Make some fake data using the following code

x=-10:0.1:10; y=cos(pi*(x)/10)+0.1*rand(1,length(x));

Save it to a text file called data.fil in a two-column format. Then findthe best fit of this data to the following functional form

y(x) = a1sech(a2x)+a3

You may use the code in fitter.m, leastsq.m, and funcfit.m fromIntroduction to Matlab as a reference, but type all your code fromscratch so you learn how each part of the code works.

(c) Rewrite your code from (b) to use anonymous functions instead ofm-file functions for both the error function and the fit function. Forsimple function fitting, we suggest you use the anonymous functionapproach because it keeps things cleaner and all contained in a singlefile. However, if your fit function requires logic (e.g. a piece-wisefunction), you’ll need to use the longer m-file format.

Page 41: computational physics 330 - Physics and Astronomy - Brigham

Lab 8

Fourier Transforms

Interpolation and Extrapolation

P8.1 Read and work through Introduction to Matlab, Chapter 12. Type andexecute all of the material written in this kind of font. Then write aMatlab script that creates coarse and fine grids for sin x like this

x=0:2*pi; y=sin(x);

xfine=-2*pi:0.1:2*pi; yfine=sin(xfine);

Use linear interpolation to plot a line using the fine grid that passes throughy(1) and y(2). Then use quadratic interpolation to plot a curve on the finegrid that passes through y(1), y(2), and y(3). Overlay four curves: thecoarse plotted as stars, the fine and the two fitted curves as lines. Use thesecurves to explain the benefits and hazards of using linear and quadraticinterpolation and extrapolation.

Fourier Transforms

Suppose that you went to a Junior High band concert with a digital recorder andmade a recording of Mary Had a Little Lamb. Your ear told you that there were awhole lot of different frequencies all piled on top of each other, but perhaps youwould like to know exactly what they were. You could display the signal on anoscilloscope, but all you would see is a bunch of wiggles. What you really want isthe spectrum: a plot of sound amplitude vs. frequency.

The mathematical method for finding the spectrum of a signal f (t) is theFourier transform

g (ω) = 1p2π

∫ ∞

−∞f (t )e iωt d t (8.1)

If you remember Euler’s relation e iωt = cos(ωt)+ i sin(ωt), you can see that thereal part of g (ω) is the overlap of your signal with cos(ωt) and the imaginarypart of g (ω) is the overlap with sin(ωt ).1 Often, we aren’t interested in the phaseinformation provided by the complex nature of g (ω), so we just look at the powerspectrum P (ω)

P (ω) = |g (ω)|2 (8.2)

P (ω) gives the signal intensity as a function of frequency without any phaseinformation. In this lab, we will learn how to make these types of plots.

1People often work with complex signals, in which case this separation is less clear.

35

Page 42: computational physics 330 - Physics and Astronomy - Brigham

36 Computational Physics 330

FFTs and Fourier TransformsPower Spectrum (linear scale)

Power Spectrum (log scale)

Figure 8.1 The power spectrum ofthe first four notes of Beethoven’s5th symphony.

P8.2 Read and work through Introduction to Matlab, Chapter 13. Type andexecute all of the material written in this kind of font.

P8.3 On the class web site is a file called “Beethoven.wav” that has the first fournotes of Beethoven’s 5th symphony. Save it to your computer and listen toit. Load the sound waveform into the matrix f using

f = wavread('beethoven.wav');

Then construct the corresponding t time series by noting that the recordingwas sampled at 11025 points/second. Plot the signal versus time and plotits power spectrum versus ν (not ω) over the range 0-1000 Hz with both alinear scale and with semilogy. (You should get in the habit of looking atspectra with a log scale to see structure that may not be evident on a linearscale.)

Now we need to make sense of the spectrum. The short notes at the begin-ning of the music are the note “G" (repeated three times) played in octavesby the violins/violas (400 Hz), cellos (200 Hz), and basses (100 Hz). Thelast note is an “E-flat,” again played in octaves by the various stringed in-struments (312 Hz, 156 Hz, and 78 Hz). Identify each of these peaks on thespectrum, and explain what their relative amplitudes mean.

Note that there are also smaller peaks at 234 Hz, 468 Hz, 624 Hz, 800 Hz,and 936 Hz. Explain where these extra peaks come from, and how each ofthe smaller peaks are connected to the notes in the four-note theme (seeFig. 8.2).

Figure 8.2 A string’s fundamen-tal mode of vibration has nodesat the ends and an antinode inthe middle. However, the stringcan also vibrate in harmonicmodes with nodes between theends. When a musician dragsa bow across a string, she ex-cites mostly the fundamen-tal, but the harmonics are alsopresent. The frequencies of thesemodes are: ν0 = fundamental,2ν0 = second harmonic, 3ν0 =third harmonic, etc.

The Uncertainty Principle

The uncertainty principle connects the duration of a signal in time with thespread of its spectrum. It was made famous in quantum mechanics by WernerHeisenberg, but it is really an idea from classical wave physics2 which we canunderstand by using the fft.

Suppose that we have a time signal which has a frequency ω0, but which onlylasts for a finite time ∆t . For example, consider the Gaussian function

f (t ) = cos(ω0t )e−(t−t0)2/W 2(8.3)

which has a “bump" centered at t0 with a width controlled by W . Because thesignal oscillates at ω0 we would expect to see a peak in the spectrum at ω=ω0.This frequency peak also has a well-defined width, and this width is related to thewidth of the signal in time through the uncertainty principle.

2The weirdness of quantum comes not from the fact that waves obey the uncertainty principle,but from the idea that things like electrons behave like waves.

Page 43: computational physics 330 - Physics and Astronomy - Brigham

Lab 8 Fourier Transforms 37

P8.4 Write a Matlab script to build f (t) from Eq. (8.3), with t0 chosen so thatthe bump is in the center of your time window. Plot f (t) and its powerspectrum for ω0 = 200 s−1 and W = 10, 1, and 0.1.

Choose appropriate values for your number of points N and your time stepτ so that

(i) fft will run fast

(ii) you can see frequencies up to ω= 400 s−1 without aliasing trouble

(iii) your spectral resolution will be at least dω= 0.2 s−1.W ∆t ∆ωplot ∆t∆ωplot

101

0.1

Table 8.1 Enter your data here

To see where the uncertainty principle is lurking in these plots, visuallymeasure and write down the full width at half maximum (FWHM) of thetime signal (∆t) and FWHM of the frequency peak (∆ωplot). Write thesemeasurements in Table 8.1 for each value of W . Then deduce a rough linear“uncertainty” relation between the width of the time signal and the width ofthe frequency peak from this data.3

You have probably experienced the uncertainty principle when listening tomusic. For a musical instrument to play a nice-sounding note the width of itsspectrum must be narrow relative to the location of the peak. So for a flute playinga high note at ω= 6000 s−1 to produce a spectrum with, say, a 1% width requires∆ω= (0.01)(6000 s−1) = 60 s−1. Then the uncertainty principle tells us that thisnote can be produced by only holding it for the relatively short time of

∆t ≈ 1

60= 0.017 s

where we have arbitrarily chosen ∆ω∆t = 1 to make the calculation. But whena tuba plays a low note around ω = 200 s−1, the same calculation using ∆ω =(200)(.01) = 2 gives a note-duration of only

∆t ≈ 1π

∆ω≈ 1

2= 0.5 s

Now tubas can play faster than this, but if you listen carefully, when they dotheir sound becomes “muddy”, which simply means that the note isn’t a very purefrequency, corresponding to a wide frequency peak.4 Your ear/brain system alsohelps you out here. It is pretty talented at turning lousy signals into music, so youcan still enjoy “Flight of the Bumblebee” even when played by a tuba.5

You can also hear this effect simply by clapping your hands. If you cup yourhands when you clap, you trap a lot of air, which responds rather slowly to your

3This is not a mathematically rigorous uncertainty relation, but it illustrates the idea.4The length of the tuba also contributes to the “muddyness” of the sound, since it takes a while

for sound to propagate back and forth between the mouthpiece and the bell and set up the standingwave. This causes a messy “attack" transient at the beginning of each note, which means you haveless of the sustained pitch to listen to.

5At tuba frequencies, your ear/brain system can perceive pitch for pulses containing only a fewcycles.

Page 44: computational physics 330 - Physics and Astronomy - Brigham

38 Computational Physics 330

clap. This makes a larger value of ∆t , which in turn means that ∆ω is smaller,corresponding to the low frequencies that make up the low, hollow boom of acupped clap. But if you slap your third and fourth fingers quickly on your palmyou trap almost no air, resulting in a very small ∆t , and hence, via the uncertaintyprinciple, a larger ∆ω. And a larger ∆ω means a higher set of frequencies in thesound of your clap, which you can clearly hear as a higher-pitched burst of sound.

Windowing

Review the material on windowing in Introduction to Matlab, then work throughthe following problem.

P8.5 Modify Listing 14.1 in Introduction to Matlab so that it uses the followingtime signal

f=sin(t)+.5*sin(3*t)+.4*sin(3.01*t)+.7*sin(4*t)+.2*sin(6*t);

Plot the power spectrum versusω and verify the relative amplitude problemdiscussed in the windowing section in Introduction to Matlab. To make theratio issue clear, normalize the spectrum so the biggest peak has height 1(i.e. plot P/max(P) instead of P).

Multiply the time signal by a Gaussian window function like this

win = window(@gausswin,length(f),alpha)'; f = f .* win;

The transpose operator (') at the end of the first line switches the windowfrom a column vector to a row vector so that the multiplication works. Theparameter alpha is specific to a Gaussian window, and is related to Eq. (8.3)via α∝ 1/W —i.e. a bigger α creates a narrower signal in time. Try severalvalues of alpha and look at plots of win and f.*win to see what the windowfunction does.

Make the window really narrow with alpha=25 and plot the power spec-trum of f.*win. Look at the peaks at ω= 1,4,6, and verify that the relativeamplitudes are now right on. (Remember that power is proportional toamplitude squared.) But what happened to the peaks atω= 3 andω= 3.01?We’ve made the peaks so broad that they’ve smooshed into each other dueto leakage. Find an alpha that is a good compromise between getting theright peak amplitude and maintaining good resolution. Explain the con-cepts of windowing and leakage, and tell how they relate to resolving theheight and width of closely spaced peaks.

P8.6 Use Matlab to numerically verify the trig identity cos(4t ) = 3/8+(1/2)cos(2t )+(1/8)cos(4t ). You will need to choose an appropriate time series and win-dow function to see the relationships accurately.

Page 45: computational physics 330 - Physics and Astronomy - Brigham

Lab 9

Pumping a Swing

There are two ways to pump a playground swing: angular momentum pump-ing and parametric oscillation. In this lab we’ll study and numerically model bothmethods.

Pumping With Angular Momentum

You are probably most familiar with angular momentum pumping. In this tech-nique, you sit on the seat and lean back, then lean forward, and lean back, etc. Youenhance angular momentum pumping when you stretch your legs out in front asyou swing forward and lean back, then tuck your legs back under as you swingbackward and lean forward. You can see why this works by imagining yourselfsuspended in outer space with your arms extended to the side. If you were tomove your right arm up and your left arm down, your body would twist sidewaysin the opposite direction to conserve angular momentum. Now imagine doingthe same thing with your arms while sitting on a swing. When your body twistsopposite to your arms to try to conserve angular momentum, friction betweenyour jeans and the swing seat will drag the swing with your body and you willstart the swing moving to the side.

Usually you want to pump a swing forward and backward rather, rather thanside to side. Since your torso and legs have more mass than your arms, you cando a better job of pumping the swing by leaning your body and moving your legsthan you can by waving your arms. When you twist your body backward, youexert a torque on the swing in the forward direction, and when you sit up againyou create a torque in the other direction. When you repeat these motions at theresonant frequency ω0 of the swing, you will be resonantly driving the pendulum,as we discussed in lab 7. This seems to be something that kids on a playgroundjust do without knowing any physics at all.

Figure 9.1 A simple model of aswing being pumped from theseated position.

To see how this works analytically, consider a the model of a swinger shown inFig. 9.1.1 The overall position of the swing is described by θ. The swinger is repre-sented by the masses m1, m2, and m3 and the possibility for the swinger to twistis represented by φ. If we make the assumption m2`2 = m3`3, the Lagrangian forthis system simplifies to

L = 1

2I1θ

2 + 1

2I2(θ+ φ)2 +M g`1 cosθ (9.1)

where M = m1 +m2 +m3, I1 = M`21, and I2 = m2`

22 +m3`

23.

1This model is taken from W. B. Case and M. A. Swanson, “The pumping of a swing from theseated position", American Journal of Physics 58, 463-467 (1990).

39

Page 46: computational physics 330 - Physics and Astronomy - Brigham

40 Computational Physics 330

P9.1 On paper, use the Lagrangian equation of motion for θ, i.e.

∂L

∂θ− d

d t

(∂L

∂θ

)= 0

to generate the equation of motion for θ. Then assume that the swingertwists harmonically, with

φ(t ) = A+ A cos(ωφt ) (9.2)

and show that the equation of motion becomes

θ+ω20 sinθ =αcos(ωφt ) (9.3)

where

ω20 =

M g`1

I1 + I2α=

I2 Aω2φ

I1 + I2(9.4)

Compare with Eq. (7.10) and confirm that this is the equation for a drivenpendulum.

P9.2 Add some friction to Eq. (9.3) by appending a linear damping term −γθ onthe right-hand side, and then solve the modified equation numerically us-ing Matlab. Use the following ballpark numbers for a child on a playgroundswing: `1 = 2 m, m1 = m2 = m3 = 10 kg, `2 = `3 = 0.5 m, and A = 0.5 rad(about 30). By experiment with a backyard swing, we find that γ= 0.1 s−1

is reasonable. Start from at-rest conditions and pump with ωp =ωφ =ω0.Plot the solution from t = 0 to t = 800 s and note that it comes to a steadystate amplitude as driving and damping balance. Then use the followingcode to animate the pumping process.

Listing 9.1 (pumpanimate.m)

% Put the code solving the equation above. The code below assumes

% that you have evenly spaced time steps with the following variables

% te -> time array

% xe -> angle theta

% wp -> the pumping frequency

% A -> the pumping amplitude

% l1 -> the main swing length

% l2 -> the head-to-middle and middle-to-foot length

tau=te(2)-te(1); L = l1+l2;

for istep=1:length(te)

% Position of swing relative to the pivot

xswing=l1*sin(xe(istep));

yswing=-l1*cos(xe(istep));

% position of head/legs with respect to swing

phi=A + A*sin(wp*te(istep));

xpers=l2*sin(phi);

Page 47: computational physics 330 - Physics and Astronomy - Brigham

Lab 9 Pumping a Swing 41

ypers=l2*cos(phi);

% Plot the swing and the swinger

plot([0, xswing],[L,L+yswing],...

[xswing+xpers,xswing-xpers],[L+yswing-ypers,L+yswing+ypers])

% Make the x and y dimensions scale equally

axis([-L/2 L/2 0 L])

axis square

% We'd like the plots frames to show at intervals of tau so the movie

% matches the physical time scale. However, the calculations

% and plotting take some time, so we decrease the pause a bit.

% Depending on the speed of your computer, you may need to adjust

% this offset some.

pause(tau-0.01)

end

Pumping With Parametric Oscillations

You can also pump a swing by standing on the seat and doing deep knee bends.As you start to swing forward you bend your knees and then stand up hard asyou go through the bottom of the motion. When you start back you repeat thismotion by bending your knees and then standing up hard as you go backwardthrough the bottom of your motion.2 This was easy to do on the solid woodenseats that swings used to have. However, after a couple of generations of kidsgetting their teeth knocked out by these wicked flying planks, playgrounds putin soft flexible seats. These seats are safer, but they are hard to stand on whilemoving your body up and down, so you may not have pumped a swing this way.Nevertheless, it is a very good way to pump a swing, although it seems a bitmysterious since no rotation is taking place. All you do is move your center ofmass up and down vertically and rotation of the swing magically appears. Thename of this mysterious technique is parametric oscillation.

The so-called parametric oscillator equation is 3

x +γx +ω20(1+εcos(ωp t ))x = 0 . (9.5)

Notice that this is different from a driven oscillator because the oscillating termcos(ωp t ) is multiplied by x(t). What is happening here is that the natural fre-quency (one of the system parameters) is wiggling in time, which is why this iscalled a parametric oscillator. In the case of a swing (which is really just a pen-dulum) you are changing the distance ` from the top of the chain to your center

2 There are some nice videos of pumping a swing this way at http://retro.grinnell.edu/academic/physics/faculty/case/swing.

3L. D. Landau and E. M. Lifshitz Mechanics (Pergamon Press, New York, 1976), p. 80-83, and M.Abramowitz and I. A. Stegun Handbook of Mathematical Functions (Dover, New York, 1971), Chap.20.

Page 48: computational physics 330 - Physics and Astronomy - Brigham

42 Computational Physics 330

of mass. Since the natural frequency of a pendulum is given by ω20 = g /`, as you

wiggle your center of mass you are wiggling the natural frequency. Equation (9.5)is simpler than the real equation for a pendulum. We will do the pendulum cor-rectly later in this lab, but for small oscillation angles of the swing Eq. (9.5) gives areasonable approximation to the the motion of a swing.

P9.3 (a) Use Matlab to solve Eq. (9.5) with initial conditions x(0) = 0 andv(0) = 1, and parameters ω0 = 1, γ = 0, ε = 0.1, and ωp = 1.1. Plotthe solution x(t ) for a long enough time that you can see that nothingmuch happens except wiggles with some beating between the naturalmotion at ω0 and the parametric drive at ωp .

Figure 9.2 Pumped swing instabil-ity.

Then run your code again with ω0 = 1, ωp = 1, γ = 0, and ε = 0.1.This matches the pumping frequency with the natural frequency ofthe swing, something you might expect would resonantly drive theoscillator. Verify that the system is only weakly unstable (meaning thatthe motion slowly grows exponentially with time.) You might have torun for a long time to see this instability.

(b) Now run your Matlab code again withωp = 2 and watch what happens.You should reproduce Fig. 9.2. Verify that ωp = 2ω0 is more unstable(i.e. the amplitude grows faster) than ωp = ω0. Once you see the2ω0 instability on your screen, come observe it with the physicalpendulum at the front of the class.

(c) Show by numerical experimentation that the oscillator is unstableat ωp = 2ω0 for all choices of ε, but that the instability growth rate issmall for small ε.

(d) Show that when ωp is not quite 2ω0 the oscillator is stable for small ε,but that when ε exceeds some threshold, it becomes unstable again.Find this threshold value for ωp = 2.05ω0 and for ωp = 1.95ω0.

(e) Now add damping by setting γ= 0.03 and show that there is a thresh-old value of ε even at ωp = 2ω0. Find it by numerical experimentation.

You should have discovered by now that the best way to parametrically drivean oscillator is to use ωp = 2ω0. Is this what you do when you pump a swing bystanding on the seat? Think about how often you move your center of mass upand down in one period of the swing and explain to your TA how ωp and ω0 arerelated as you do this.

Interpreting the Spectrum of the Parametric Oscillator

To gain some insight into whyωp = 2ω0 is more unstable thanωp =ω0 it is helpfulto look at the power spectrum of x(t ) for the parametric oscillator. In doing thisanalysis we will use a form of perturbation theory which all physicists love, butwhich you may not have seen. So before we look at the spectrum of x(t), let’s do aperturbation theory problem as a warm-up.

Page 49: computational physics 330 - Physics and Astronomy - Brigham

Lab 9 Pumping a Swing 43

Suppose that you wanted to solve the equation

x3 = 1+0.1ex (9.6)

for a real solution near x = 1. This equation is horrible, but if it weren’t for the ex

term, it wouldn’t be so bad: x3 = 1 so x = 1. But look; the exponential term is notso important since it is multiplied by 0.1, which is small. Shouldn’t we be able toexploit this smallness somehow? The answer is yes, and here is how to do it, stepby step.

Step 0: Ignore the small ex term altogether and just solve the easy equation:

x3 = 1 ⇒ x0 = 1 (9.7)

We call this beginning, and easiest, solution x0 to keep track of which stepwe are in.

Step 1: We will now get a better approximation to the solution by writing theequation down again, but with a twist in the small exponential term. Wewill guess that since it is small, it might be OK to replace the horrible ex byan approximate version of it, namely ex0 :

x3 = 1+0.1ex0 ⇒ x3 = 1+0.1e1 ⇒ x1 = (1+0.1e1)1/3 (9.8)

The replacing of ex by ex0 again made the equation easy to solve, which isgood, but we still haven’t found the correct solution.

Step 2: To further improve our solution we repeat step 1, writing

x3 = 1+0.1ex1 ⇒ x3 = 1+0.1exp[(1+0.1e1)1/3] (9.9)

⇒ x2 = (1+0.1exp[(1+0.1e1)1/3] )1/3

P9.4 This procedure starts to look ugly analytically, but if we just want a nu-merical answer there is no point in writing all of this out. Solve Eq. 9.6 bycontinuing this step by step approach all the way to 15 significant figures inthe Matlab command window by typing

x=1 x=(1+0.1*exp(x))^(1/3)

and then using the ↑ key to repeat the second step over and over again. Justwatch the result for x and quit when the digits in the answer quit changing.You should find that the procedure converges to x = 1.090733645657879;verify that this is the solution to the equation

x3 = 1+0.1ex

This is a very powerful trick and we will now use it to understand the paramet-ric instability at ωp = 2ω0.

Page 50: computational physics 330 - Physics and Astronomy - Brigham

44 Computational Physics 330

P9.5 Using x(0) = 0, v(0) = 1, ω0 = 1, ωp = 1.3, γ= 0, and ε= 0.3, run your modelfrom t = 0 to t = 500 with 214 equally spaced time steps. Take the Fouriertransform and display its power spectrum using a semilogy plot. Ourupcoming analysis will be easier if we consider negative frequencies, souse ft.m from Chapter 14 of Introduction to Matlab and construct yourfrequency array appropriately.

You should immediately notice the big peaks at ±ω0. This is not a surprisebecause what we have is an oscillator at frequency ω0 = 1 plus a smallperturbation of size ε at frequency ωp = 1.3. But if you look for a peak atω= 1.3, you won’t find it, even though there are plenty of other peaks. Ourjob now is to explain why these other peaks are where they are.

Since ε is small and the damping is weak, let’s begin by ignoring them both(ε= 0 and γ= 0). (This is step 0 in our perturbation analysis.) Then note that withthese simplifications Eq. (9.5) is solved by

x0(t ) = A cos(ω0t ) (9.10)

Now we will proceed by perturbation theory as we did in the previous problem,like this. Make a more precise guess at the solution by writing Eq. (9.5) downagain, but with x0 in place of x in the small term ω2

0εcos(ωp t )x:

x +γx +ω20(1+εcos(ωp t ))x0 = 0 ⇒ (9.11)

x +γx +ω20x ≈−εω2

0 cos(ωp t ))x0

With x0 = A cos(ω0t ) this is just a complicated version of the driven harmonicoscillator.

P9.6 Use Mathematica to solve this equation with γ= 0. You may need to recallthat inhomogeneous linear differential equations like this have solutionsof the form x = xh + xp , where xh is the homogeneous solution (withoutthe parametric driving term) and where xp is the particular solution withthe driving term included. Mathematica will give you a pretty complicatedanswer, but if you look at it closely you will see that the homogeneoussolution is just our friend x0 = A cos(w0t ) and that the particular solution(the messy part) can be written as a sum of terms that involve sines andcosines at new frequencies. It’s as if the driving force had a split personalityinvolving more than one driving frequency. This is exactly right, as you cansee by using the identity

cosαcosβ= 1

2

(cos(α+β)+cos(α−β)

)to rewrite the driving term on the right side of the differential equationabove. Do the math and see what frequencies turn up. Can you seethese“sideband” frequencies in your spectrum from P9.5 and in your Math-ematica solution?

Page 51: computational physics 330 - Physics and Astronomy - Brigham

Lab 9 Pumping a Swing 45

In this first-order perturbation theory we see that in addition to the peak atω0,there are two other, smaller, sideband contributions at (ω0 +ωp ) and at (ω0 −ωp ).If we now take the second step in perturbation theory the driving term will be

−εω0 cos(ωp t ))x1 . (9.12)

If you use the trig identity above for this second step in the perturbation theory,you will find that each of the frequency components from the first-order step ismultiplied by cosωp t and that they then produce new sidebands shifted againfrom the first-order frequencies ±ωp . These second-order sidebands are smallerin magnitude than the first-order sidebands because in each step the new drivingterm is multipled by another factor of ε. But they are clearly there in the spectrum.This procedure, of course, never ends, so it is easy to see that this equation canproduce a very rich spectrum.

Now, what does this have to do with the observed instability atωp = 2ω0? Well,as we saw in first-order perturbation theory, when we parametrically oscillate atωp the system looks like a driven oscillator with driving frequencies at ω0 ±ωp .When ωp = 2ω0, the sum and difference frequencies fall at 3ω0 and −ω0. Sinceone of the apparent driving frequencies is at ω0 (note that −ω0 is just as resonantas ω0), the system feeds back on itself and is unstable.

This effect also allows us to see why ωp =ω0 is not the most unstable choice.The reason is that with this choice the sideband frequencies are 0 and 2ω0, neitherone of which is resonant. But the second-order sidebands are −ω0, ω0, ω0, and3ω0. Three out of four come back to ω0 in second order, so there is a possibility ofinstability due to this nonlinear resonance. But because it takes two perturbationsteps to get to this resonance, and since each step involves another power of ε,this choice for ωp is less unstable.

P9.7 Explain all of the frequency peaks in your spectrum from P9.5 using theconcepts explained above. Explain what the amplitudes of the variouspeaks mean and how the ωp = 2ω0 instability arises.

Parametrically unstable pendulum

When you pump a real swing, your oscillation amplitude doesn’t become infinitebecause the swing is a pendulum, not a harmonic oscillator. Using the Lagrangianformulation of mechanics to obtain the equation of motion of a pendulum whoselength `(t) is changing with time, and adding some damping because of airfriction, gives us the equation

θ+2˙

`θ+γθ+ g

`sinθ = 0 . (9.13)

If we let the length change sinusoidally at frequency ωp by only the small amount∆L about the constant length L0, then

`(t ) = L0 +∆L cosωp t . (9.14)

Page 52: computational physics 330 - Physics and Astronomy - Brigham

46 Computational Physics 330

P9.8 Use Matlab to solve Eqs. (9.13) with (9.14) using the following realisticparameter values. A typical backyard swing has a length of about L0 = 2 m.As you do deep knee bends you move most of your mass up and down, sothe ∆L of your parametric oscillation is about half the distance you dropyour body during the bend. Use γ = 0.1 s−1 again for the decay. In yournumerical solution gradually increase∆L from zero up to around 0.3 m withωp = 2ω0 and find the threshhold value of ∆L at which the swing becomesunstable. (Explain to your TA why the pendulum amplitude doesn’t justkeep getting bigger forever.)

Page 53: computational physics 330 - Physics and Astronomy - Brigham

Lab 10

Chaos

The van der Pol Oscillator

Consider the following non-linear oscillator equation, called the van der Poloscillator:1

x −ε(`2 −x2)x +ω20x = 0 . (10.1)

This is a simple model differential equation for systems that have an externalsource of energy which causes the resting state (x = 0, v = 0) to be unstable,but which also have sufficient damping that the instability cannot grow to anarbitrarily large amplitude.

Begin by studying Eq. (10.1) and convincing yourself that the resting state isindeed unstable, but that large amplitude motion is damped (on average). Youcan’t see that x = 0, v = 0 is unstable by starting the system there and waiting forsomething to happen, because nothing will happen. This is an equilibrium pointand if you start it there it will remain there forever. To test for stability, start thesystem in a point very close to equilibrium and watch to see if it stays near theequilibrium point, or runs away from it. Appropriate initial conditions to testfor stability might be x = 0.0001, v = 0. The phase-space flow plot, made withquiver, in Fig. 10.1 illustrates these two features. Notice the arrows leading awayfrom the origin and the general inward flow at the outer edges of the picture. Theflow is not uniformly inward, however, and later in this lab you will see the effectof the squeezed inward flow patterns visible in the figure.

−3 −2 −1 0 1 2 3−4

−3

−2

−1

0

1

2

3

4

x

v

Van der Pol Phase Space

Figure 10.1 Flow in phase spacefor the Van der Pol oscillator withω0 = 1, `= 1, and ε= 1.P10.1 (a) Use Matlab’s ode45 to solve Eq. (10.1) numerically for ε = 0.3, ω0 =

1.3, and ` = 1. Use options=odeset('RelTol',1e-5) to set theaccuracy of ode45 at a level that will make it possible to do long runsin a reasonable time. (We would normally use a smaller tolerancethan this, but we only have 3 hours together). Make both a plot of x vs.t as well as a phase space plot of v vs. x for a bunch of different initialconditions. Notice that the phase space plot eventually settles on thesame curve for any initial conditions you pick. The phase space curveon which the solutions settle is called a limit cycle

(b) Repeat part (a) for ε = 1 and ε = 20 and note how the limit cyclechanges shape. Also plot the power spectrum of x(t ) with semilogy

using an axis command to display the spectrum fromω0 = 0 toω0 = 20and note where the major peaks are.

1R. Baierlein, Newtonian Dynamics (McGraw Hill, New York, 1983), p. 88-93.

47

Page 54: computational physics 330 - Physics and Astronomy - Brigham

48 Computational Physics 330

Limit Cycles and Attractors

The limit cycle you observed in this problem is a simple example of an attractorin phase space. An attractor is a curve in the phase-space of the differentialequation to which many different solutions (having different initial conditions)tend. For instance, for the damped un-driven harmonic oscillator the attractor isjust the state of no motion: x = 0, v = 0, because all solutions end up here. For thedriven damped harmonic oscillator the attractor is more interesting: it is the finaldriven steady state of the oscillator, which looks like an ellipse in phase space.Since this attractor is not a single point, we also call it a limit-cycle. For the vanDer Pol equation the attractor is the oddly-shaped curve (or limit-cycle) in the(x, v) phase space to which all solutions tend.

Sometimes an attractor is not a single curve, but rather a very complex struc-ture, like the famous Lorenz attractor (which you can explore a little bit by typinglorenz at the command prompt in Matlab). These kind of attractors are calledstrange attractors, and are examples of chaotic systems. We’ll study chaos later inthis lab and you will see other examples of attractors, but none of the attractorsencountered in this lab are strange attractors (except the Lorenz attractor).

P10.2 Now let’s add a driving force to the van der Pol oscillator, like this:

x −ε(`2 −x2)x +ω20x = A cosωt . (10.2)

Using `= 1, ε= 2, ω0 = 1.3, and ω= 1.4, gradually increase A from 0 to 1.5and watch what happens to the power spectrum of x(t ). Change A by stepslarge enough to see qualitative changes, i.e., don’t do A = 0.01, A = 0.02,A = 0.03, etc.

You should find that as A is increased the limit cycle becomes fuzzy and thatthe power spectrum becomes increasingly filled with spikes. Finally, aroundA = 1.25 → 1.27 the power spectrum becomes so complicated that it is fuzzytoo (use the zoom feature on the spectrum to see that the spectrum is madeup of many tiny peaks). And then, quite abruptly, at about A = 1.28 theoscillator becomes slaved to the drive, meaning that the oscillator vibratesat the driving frequency ω= 1.4 and its harmonics, making the spectrumsimple again. (Look carefully at the power spectrum to see that this is true).

Entrainment

The kind of behavior illustrated in P10.2 is called entrainment, in which an oscil-lator becomes synchronized to another periodic signal. An important example ofa system like this is the human heart. The heart has an external source of power,has an unstable resting state (it wants to beat rather than sit still), and, normally, astable limit cycle (thump-Thump, thump-Thump,...). Sometimes this stable limitcycle becomes irregular, in which case it is desirable to supply a periodic driving

Page 55: computational physics 330 - Physics and Astronomy - Brigham

Lab 10 Chaos 49

signal via a pacemaker which, if strong enough, can force the heart to becomeentrained with it, restoring a stable limit cycle, albeit at a frequency determinedby the pacemaker rather than by the physical needs of the patient.

Dynamical Chaos

Now let’s switch gears a bit and take a brief tour through one of the most excitingareas in the study of differential equations: dynamical chaos. A chaotic system isone where dynamical variables (e.g. position and velocity) behave in seeminglyerratic ways and exhibit extreme sensitivity to initial conditions. Chaotic systemsare deterministic, since a given set of parameters and initial conditions repro-duce the same motion, but it is usually difficult to predict how tiny variations inparameters or initial conditions will affect the motion.

Chaotic systems have been known and studied for a long time. For instance,it comes as no surprise that when you have 1023 atoms bouncing around inside acontainer, hitting the walls and hitting each other, that the motion of any givenatom is pretty chaotic. But in the middle of the twentieth century it was discoveredthat even simple systems can be chaotic. For instance, here is the apparentlynice, smooth, and well-behaved differential equation for the driven dampedpendulum:

d 2θ

d t 2 +γθ+ω20 sinθ = A cosωt . (10.3)

This system has only two degrees of freedom (way less than 1023) and all of thefunctions that appear in it are nice and smooth. But for certain choices of A, ω,ω0, and γ the solutions of this differential equation are almost as unpredictableas the motion of an atom in a gas.

Chaos is hard to study because that old standby of physical theory, the for-mula, is not of much help. If we had a formula for the solution of this differentialequation its behavior would be perfectly predictable and un-chaotic. Since thedynamics in chaotic systems are not represented by analytic formulas, their so-lution had to wait for computers to be invented and to become powerful. Thecomputers we will use in this laboratory are more powerful than the computerswe used to send men to the moon and to design nuclear weapons in the 1960sand 1970s, so we have all the computing power we need to at least be introducedto this fascinating field.

P10.3 A simple system in which chaos can be observed is a particle moving in apotential well with two low spots:

U (x) =−x2

2+ x4

4. (10.4)

(a) Plot this potential vs. x and locate the two stable equilibrium points(the one in the middle is unstable).

Page 56: computational physics 330 - Physics and Astronomy - Brigham

50 Computational Physics 330

(b) Let a particle have mass m = 1 and use the force relation

Fx =−∂U

∂x(10.5)

to derive the equation of motion of the particle. Then write a Matlabscript and a function that employs ode45 to solve for the motion of theparticle. Use options=odeset('RelTol',1e-6) to set the accuracyof ode45. Try several different initial conditions and watch how theparticle behaves in this double well. Look at the motion in phase spacefor enough different initial conditions that you can see the transitionfrom motion in one well or the other to motion that travels back andforth between the wells.

(c) Now add a driving force of the form F = A cos2t and also include alinear damping force Fd amp =−mγx with γ= 0.4. Use initial condi-tions x(0) = 1, v(0) = 0, and make a series of runs with A graduallyincreasing until you observe chaotic behavior. (The transition fromregular motion to chaos occurs between A = 0.7 and A = 0.8). Runfrom t = 0 to t = 1000. A plot of x(t) should show random jumpingbetween the left and right sides of the double well, as illustrated inFig. 10.2. For each run make a plot of the power spectrum of x(t).Show the TA how your plots illustrate intermittency and 1/ f noise(described below).

0 500 1000 1500 2000

−1

−0.5

0

0.5

1

t

x

Intermittent Chaos

Figure 10.2 Intermittent randombouncing between the two wells.

(d) With A = 0.9 do two runs, one with initial conditions x(0) = 1, v(0) = 0,and the other with x(0) = 1.000001 and v(0) = 0. Plot x(t) for eachof these cases, and explain to the TA how these plots illustrate thebutterfly effect (described below).

Intermittency, 1/ f Noise, and the Butterfly Effect

The random switching back and forth between equilibrium positions observed inP10.3(c) is called intermittency and is one of standard ways that regular systemsbecome chaotic. As the motion becomes chaotic you should also see an increasein the spectrum near ω= 0. This low frequency peak in the spectrum is one of thesymptoms of chaos (called “1/ f noise”) and is a direct consequence of the slowrandom switching of intermittency.

Another hallmark of chaotic systems is the so-called “butterfly effect” (il-lustrated in P10.3(d)), where very small changes in the initial conditions causelarge differences in the motion. This effect was discovered by Edward Lorenz(for whom the Lorenz attractor is named), who was a meteorologist that studiednumerical models for weather prediction in the early 1960s. He noticed that verytiny differences in initial conditions (too small to even be measured) led to vastlydifferent outcomes in his model. The effect gets its name from a talk that he gavein 1972 titled “Predictability: Does the Flap of a Butterfly’s Wings in Brazil set off aTornado in Texas?".

Page 57: computational physics 330 - Physics and Astronomy - Brigham

Lab 10 Chaos 51

P10.4 (a) Make a phase space plot for the system in P10.3(c) with A = 0.96. Youshould find that the chaotic behavior quiets down and is replaced bya limit cycle in phase space. It will be difficult to see the limit cycle onthe phase space plot because of the messy transients at the beginning.To eliminate the transients make the phase space plot like this (Wechose to skip the first 60%–you can try your own value):

N=length(x);

n1=ceil(.6*N); % n1 starts 60% into the array

plot(x(n1:N),v(n1:N));

(b) Make another phase space plot at A = 1.30. The single limit cycleshould be replaced by a 2-cycle (two loops in phase space beforerepeating);

Note: to really see the multiple character of these cycles, use the zoomfeature in the plot window to look carefully at them, especially nearthe tight loops. This is shown in Fig. 10.3 for the 4-cycle state. Inthe upper window the full time history is shown from the beginningwhile in the lower window the late-time final state in the windowfrom the upper frame is shown. There are clearly 4 repeated loopsin phase space, so this is called a 4-cycle. This is an example of thefamous “period-doubling route” to chaos, as well as an example ofregular behavior in a region of parameter space where you might haveexpected chaos.

−1.5 −1 −0.5 0 0.5 1 1.5

−1

0

1

x

v

4−cycle

−0.8 −0.75 −0.7 −0.65 −0.6 −0.55 −0.5−0.1

−0.05

0

0.05

x

v

Figure 10.3 Full time history, thenfinal 4-cycle state from the smallwindow. There are fewer loops inthe lower trace because it is thefinal state; the extra loops in thebox in the upper trace are fromearly times.

(c) Make phase space plots of the limit cycle at A = 1.36 (a 4-cycle state),which is then replaced by an 8-cycle at A = 1.371, and then chaostakes over again.

If you run with A = 1.97, 1.99, and 2.0, you will see chaos disappearto be replaced by a 2-cycle, a 4-cycle, and an 8-cycle. Beyond 2 therechaos again.

At A = 3 the amplitude is large enough that the oscillator becomesslaved to the drive and we have entrainment. You might think thatlarge A would always cause entrainment, but A = 50 is chaotic, andthere are probably lots of 2,4,8,... cycles and chaotic regions as A isvaried. We ran out of patience; let us know what you find.

Note: when you run with A = 1.36 your phase-space picture may looklike an upside-down left-right flipped version of Fig. 10.3. This is OK–the differential equation is almost unchanged if (x, v) is replaced with(−x,−v). The only difference is that the driving term is replaced byits negative, which is equivalent to a phase shift of π. Such a phaseshift could occur by having the oscillator start up in a different way,which might easily happen if your initial conditions were not exactlythe same as ours. This flipped-over state is to be expected on physicalgrounds. Our picture has tight loops on the left and big loops on theright, but the potential is left-right symmetric; there should be anotherstate with tight loops on the right and big ones on the right as well.

Page 58: computational physics 330 - Physics and Astronomy - Brigham

52 Computational Physics 330

Fractals

P10.5 (a) The Fibonacci sequence Fn is defined by

F1 = 1 ; F2 = 1 ; Fn = Fn−1 +Fn−2 for n ≥ 3 (10.6)

(The first few numbers in the sequence are 1,1,2,3,5,8,13, ...). Writea loop that fills the array Fn with the first 100 values of the Fibonaccisequence.

Figure 10.4 The function plottedin P10.5

(b) Now define an array x that goes from −2π to 2π with 50,001 equallyspaced values, like this:

h=4*pi/50000;

x=-2*pi:h:2*pi;

Then write a loop that evaluates the Fourier-like series

G(x) =100∑n=1

cos(Fn x)

Fn. (10.7)

Plot this function vs. x and carefully observe its shape (this functionis shown in Fig. 10.4). Then use the zoom feature to more closelyexamine some of the smaller mountain peaks to discover that eachmountain peak contains smaller versions of itself.

If you zoom in too much you will run out of points, so now plot thefunction again using 50,001 points between x = 3.1 and x = 3.2, andzoom in again. This kind of curve is called a fractal, or fractal curve 2

and such curves are important in chaos theory.

2S. N. Rasband, Chaotic Dynamics of Nonlinear Systems (John Wiley and Sons, New York, 1990),Chap. 4, and http://sprott.physics.wisc.edu/fractals.htm

Page 59: computational physics 330 - Physics and Astronomy - Brigham

Lab 11

Coupled Nonlinear Oscillators

When two or more oscillators are hooked together, we say that they are cou-pled. 1 Our final model for driving a swing was an example of coupled pendula.In that case the rotation of the swinger was coupled to the rotation of the overallswing, which allows you to drive the swing.

In this lab we consider a different method for coupling pendula. Consider twopendula hanging from the same piece of horizontally-stretched rubber tubing.If one pendulum is held fixed and the second is displaced from equilibrium, thesecond one experiences a restoring torque from two separate sources: (a) gravityand (b) the rubber tubing. If both pendulums are displaced together each oneexperiences gravity and restoring torque from the tubing, but the tubing betweenthe two plays no role because they both twist it in the same direction. But if thependulums are displaced in opposite directions then the tubing between themis flexed, causing an extra restoring torque. This difference in restoring forcebetween the “together” and “opposite” motions is the cause of the two slightlydifferent frequencies that produce the beating you will see throughout this lab.

Coupled Equations of Motion via Lagrangian Dynamics

For small displacements, the effect of gravity (plus a small contribution from thetubing) can be modeled as restoring torsional springs with spring constants κ1

and κ2 for pendulum 1 and pendulum 2, respectively. This leads to a potentialenergy

U = 1

2κ1θ

21 +

1

2κ2θ

22 . (11.1)

The tubing also adds a coupling term to the potential energy of the form

Uc = 1

2κc (θ1 −θ2)2 (11.2)

Note that this extra restoring potential energy is zero if the angular displacementsare equal. The total potential energy is

U = 1

2κ1θ

21 +

1

2κ2θ

22 +

1

2κc (θ1 −θ2)2 . (11.3)

P11.1 Combine this potential energy function with the kinetic energy

T = 1

2I1θ1

2 + 1

2I2θ2

2(11.4)

1 G. Fowles and G. Cassiday, Analytical Mechanics (Saunders, Fort Worth, 1999), p. 443-460.

53

Page 60: computational physics 330 - Physics and Astronomy - Brigham

54 Computational Physics 330

to build the Lagrangian (L = T −U ). Use the Lagrangian equation of motion

∂L

∂qi− d

d t

(∂L

∂qi

)= 0 (11.5)

to derive equations of motion for θ1(t) and θ2(t). Then simplify theseequations by assuming that the two pendula are identical so thatκ1 = κ2 = κand I1 = I2 = I . Also eliminate the spring constants and moments of inertiain favor of frequencies according to the definitions

ω20 =

κ

I; ω2

c =κc

I. (11.6)

Finally, put these two second-order differential equations in coupled firstorder form.

If you did P11.1 correctly, you should have arrived at the following four first-order differential equations for describing the motion of the coupled-pendulumsystem:

θ1 = ω1 (11.7)

θ2 = ω2 (11.8)

ω1 = −ω20θ1 −ω2

c (θ1 −θ2) (11.9)

ω2 = −ω20θ2 −ω2

c (θ2 −θ1). (11.10)

The four variables are: the angular positions of the two pendulums θ1(t) andθ2(t ) (remember that θ = 0 corresponds to the pendulum hanging straight down)and, the angular velocities of the two pendulums ω1(t ) and ω2(t ). The parameterω0 is associated with the natural frequency of a single pendulum without anycoupling, and the parameter ωc is associated with the natural frequency of themiddle section of tubing when attached to the two pendula.

P11.2 (a) Use Mathematica to solve Eqs. (11.7)-(11.10) symbolically withoutinitial conditions to see if you can find the two separate frequenciesthat cause the beating you will see when you solve them in Matlab.

(b) Now numerically solve this system in Matlab with ω0 = 1.3 and ωc =0.3; for initial conditions let everything be zero except θ1(0) = 0.3.Make plots of θ1(t ) and θ2(t ), one above the other using subplot2 likethis:

subplot(2,1,1)

plot(te,th1e)

subplot(2,1,2)

plot(te,th2e)

0 50 100 150 200 250−1

0

1

t

θ 1

Beats

0 50 100 150 200 250−1

0

1

t

θ 2

Figure 11.1 Energy passes backand forth between θ1 and θ2 dueto beating.

Run long enough that something interesting happens, i.e., run at leastlong enough that θ2(t) becomes large, then small again. You should

2For more information about subplots, look it up via help subplot using online help in Matlab.

Page 61: computational physics 330 - Physics and Astronomy - Brigham

Lab 11 Coupled Nonlinear Oscillators 55

be looking at the beat plot in Fig. 11.1. This pattern of increasing anddecreasing amplitude in the plots of θ1(t ) and θ2(t ) is an example ofinterference beats caused by the presence of two different frequenciesin the dynamics.

(c) Run the solution out for long enough that when you take the FFT ofθ1(t ) you can see the two peaks in the power spectrum correspondingto the two frequencies whose mixing causes the beats. Verify thatthe beat frequency ωb = 2π/Tb , (where Tb is the time for one of theoscillators to be at maximum amplitude, go to zero amplitude, thencome back to maximum amplitude again) is related to the two peaksin the spectrum ω+ and ω− by

ωb =ω+−ω− . (11.11)

Also verify that the two frequencies you observe in the FFT are the twofrequencies predicted by your Mathematica calculation.

Note: the figure at the beginning of this lab does not have enoughoscillations in it for the FFT to work well. As a general rule, your timeplots should look solid if you want to use the FFT. A maximum timearound 2000 works fine.

(d) Now add a linear damping term to the equation of motion for pendu-lum number 2, start the system with these initial conditions: θ1(0) =0.3, θ1(0) = 0, θ2(0) = 0, θ2(0) = 0. and study the motion of the twooscillators. Use

θ2 =−γθ2 +·· · (11.12)

with γ= 0.07. Look at the plots for θ1(t) and θ2(t) and discuss whathappens to the energy that was initially put into pendulum number 1.

(e) Now drive pendulum number 1 by applying a small negative torqueN1 = −0.3 whenever θ1 is positive and θ1 is negative. You will need

t This driving force is essen-tially the same as the inter-mittent torque you apply tosomeone when you pushthem in a swing.

to use an if statement in the M-file that defines the right-hand sideof your set of differential equations to make this work. This drivingforce is similar to the escapement in a pendulum clock in which amechanical linkage allows the weights to push on the pendulum whenit is at the proper place in its motion. Think about this drive and verifythat it always puts energy into pendulum number 1.

As in part (b), don’t damp pendulum number 1; just keep the dampingin pendulum number 2. Run the code long enough that the systemcomes to a steady state in which both pendulums have constant am-plitude. Discuss the flow of energy in this system.

Coupled Wall Clocks

Now we are ready to study a very famous problem in dynamics. In the 1600sChristian Huygens observed that when two clocks are hung next to each other

Page 62: computational physics 330 - Physics and Astronomy - Brigham

56 Computational Physics 330

on a wall, they tend to synchronize with each other. Let’s see if we can make ourequations of motion do this.

P11.3 (a) Begin by making both pendulums be damped and driven as describedin P11.2(d) and (e), but remove the coupling by setting ωc = 0. Runthe code and make sure that each clock comes to its own independentsteady state.

Now add weak coupling between the two by setting ωc = 0.3 again(the slight pushes and pulls that each clock exerts on the wall is thesource of this coupling) and see if the clocks ever synchronize witheach other. (Synchronization means that the two pendulums have thesame period with some definite phase shift between them. This effectis called entrainment in the nonlinear dynamics literature).

When you do these runs, start pendulum 1 with θ1 = 1 and θ1 = 0 andtry various choices for the initial conditions of pendulum number 2.When they become entrained, check the phase difference betweenthe two clocks. (A visual inspection is probably sufficient). In yournumerical experiments, how many different phase relationships doyou observe? (Try overlaid plots of θ1 and θ2 to see the phase relation-ships). Do your in-phase and out-of-phase entrained states have thesame frequencies?

(b) According to the nonlinear dynamics literature, entrainment is aneffect that depends on the oscillators being damped, driven, andnonlinear. Where is the nonlinearity in our equations of motion?

(c) Finally, let’s make these clocks a little more realistic by (i) replacing−ω2θ by −ω2 sinθ in each equation of motion and by (ii) having theirnatural frequencies be slightly different. Do this by changingω2 in theequation of motion for pendulum 2 to 1.03ω2, 1.1ω2, and 1.25ω2 (doall three cases). You should find that entrainment is relatively robust,meaning that the clocks don’t have to have exactly the same period tosynchronize, but that if they are too different the effect is lost. Doesthis robustness depend on the strength of the coupling parameter ωc ?Comment on what your answer to this last question has to do withreal clocks on a wall.

Solving Nonlinear Equations

P11.4 Read and execute the examples in Introduction to Matlab, Chapter 14. Thencomplete the following exercises.

(a) Write a loop that makes an array containing the first 40 zeros of theBessel Function J0(x). Find these zeros by writing a loop to load themusing Matlab’s fzero command. You will have to give fzero a search

Page 63: computational physics 330 - Physics and Astronomy - Brigham

Lab 11 Coupled Nonlinear Oscillators 57

range instead of just an initial guess, and this will be easier if youremember that the zeroes of J0(x) are separated by about π.

Look through your list of zeros and make sure that there are no re-peated values. Then plot J0(x) and put a red x at every zero.

(b) Solve the following set of equations using Matlab’s fsolve command

x2 + y2 + z2 = 139x

x + y − z= 3

xp

z = (10− y)2

Page 64: computational physics 330 - Physics and Astronomy - Brigham
Page 65: computational physics 330 - Physics and Astronomy - Brigham

Lab 12

The Pendulum with a High Frequency Driving Force

Consider1 an un-driven equation of motion of the form

x =−∂V

∂x. (12.1)

For instance, a harmonic oscillator has V (x) = kx2/2m and pendulum has V (x) =−(g /L)cos x. Let the characteristic time over which this system changes appre-ciably be the period T , e.g. T = 2π/

√g /L for the pendulum. We now drive this

system with a very high frequency force that depends on both the particle positionx and time t so that the equation of motion becomes

x =−∂V

∂x+ A(x)sinωt , (12.2)

withωÀ 2π/T (12.3)

defining what we mean by high frequency. If we use our intuition (perhapsthinking about what it feels like to drive at high speed over a back-country dirtroad that has developed wash boards) we might guess that the motion describedby this differential equation would consist of some sort of slowly varying motionon the time scale T plus a high frequency low amplitude vibration at frequency ω.We make this guess precise by writing

x(t ) = X (t )+ξ(t ) , (12.4)

where X (t ) describes the slow motion (think about the car winding its way aroundcurves and over hills) and ξ(t ) describes the small amplitude high frequency oscil-lations (think about stuff in the glove compartment rattling, your teeth chattering,etc.). An example of this kind of motion is shown in Fig. 12.1. The smooth curve isX (t ) while the bumpy curve is x(t ) = X (t )+ξ(t ). The function ξ(t ) is the differencebetween the two curves.

Perturbation Theory

Because ξ(t) is caused by the sinusoidal driving force, we will see that its timeaverage is zero, and the wide separation of time scales allows us to assume that

1This analysis is borrowed from Mechanics by Landau and Lifshitz: L. D. Landau and E. M.Lifshitz Mechanics (Pergamon Press, New York, 1976), p. 93-95.

59

Page 66: computational physics 330 - Physics and Astronomy - Brigham

60 Computational Physics 330

X (t ) changes only slightly during one period of the high frequency motion. Sub-stituting Eq. (12.4) into Eq. (12.2) and expanding in small ξ through first ordergives

X + ξ=− ∂V

∂x

∣∣∣∣x=X

−ξ ∂2V

∂x2

∣∣∣∣x=X

+ A(X )sinωt +ξ ∂A

∂x

∣∣∣∣x=X

sinωt . (12.5)

We first attack this equation by looking at the high frequency terms. The termA sinωt is a big term, as is ξ because of its rapid variation in time (ξ≈−ω2ξ withω large). All of the other high frequency terms are small compared to these twobecause ξ is small, so we have (approximately)

ξ= A(X )sinωt , (12.6)

with X approximately constant because it varies so slowly. A simple integrationyields the rapidly varying position and velocity

ξ(t ) =− A(X )

ω2 sinωt ; ξ(t ) =− A(X )

ωcosωt . (12.7)

We now substitute this result into Eq. (12.5) and time average every term inthe equation over one period of the high frequency motion. Terms that containsingle powers of ξ, cosωt , or sinωt average to zero while in the last term, whichcontains sin2ωt , we may replace sin2ωt by its time average of 1/2 to obtain

X =−V ′(X )− A(X )

2ω2

d A

d X(12.8)

As you can see, the low frequency motion of the oscillator is altered by the pres-ence of this rapidly oscillating force, provided that the force depends on X . Thismeans that a simple high-frequency external force of the form A sinωt with Aconstant has no effect on the slow motion.

We are not quite finished because we haven’t discussed the initial conditions.Suppose that we have initial conditions

x(0) = x0 ; x(0) = v0 ,

Using Eq. (12.4) we have

X (0)+ξ(0) = x0 ; X (0)+ ξ(0) = v0

which can be combined with Eq. (12.7) at t = 0 to obtain the proper initial condi-tions for the slow-motion variable X :

X (0) = x0 ; X (0) = v0 + A(x0)/ω . (12.9)

With this choice of initial conditions a combined plot of x(t ) and X (t ) shows thatx(t) wiggles and slowly varies, while X (t) tracks right with it, but with all of thewiggles smoothed out.

Page 67: computational physics 330 - Physics and Astronomy - Brigham

Lab 12 The Pendulum with a High Frequency Driving Force 61

Driven Pendulum

An interesting example of this kind of system is a pendulum whose support pointvibrates rapidly up and down like this:

ysupport = b sinωt . (12.10)

A simple way to find the new equation of motion of the pendulum is to use Ein-stein’s principle of equivalence between acceleration and gravity: If the supportpoint is accelerating upward with acceleration asupport, then the pendulum willexperience a downward gravitational force −masupport. Hence we may write forthe effective acceleration of gravity acting on the pendulum asupport = ysupport =−ω2b sinωt so that the total acceleration, including ordinary gravity is

geff = g −asupport = g − ysupport = g +bω2 sinωt , (12.11)

which then leads to the equation of motion

θ =−ω20 sinθ− bω2

Lsinθ sinωt , (12.12)

where ω20 = g /L. This equation of motion matches Eq. (12.2) if we write

A(θ) =−bω2

Lsinθ , (12.13)

which then leads to the following slow time-averaged equation of motion [seeEq. (12.8)]:

Θ=−ω20 sinΘ− b2ω2

2L2 sinΘcosΘ . (12.14)

0 1 2 3 4 5−1

−0.5

0

0.5

1

t

x(t)

High−frequency Driving Force

Figure 12.1

P12.1 (a) Use Matlab’s ode45 to solve for the motion of a rapidly driven pen-dulum by solving both Eq. (12.12) and Eq. (12.14) with ω0 = 1, L = 1,b = .02, and ω= 30 with initial conditions θ(0) = 1, θ(0) = 0 and runfor a total time of 30 seconds. Overlay the plots of θ(t ) from both equa-tions to see that the averaged solution approximates the un-averagedsolution.

Now run it again with initial conditions θ(0) = 3.1, θ(0) = 0 and checkthe agreement again.

Note: The averaged solution won’t go through the middle of the wig-gles of the full solution unless you adjust the averaged initial condi-tions as shown in Eq. (12.9). When you do it right your plot shouldlook like Fig. 12.1.

(b) Now redo part (a) with everything the same except use b = .05 this time.You should be surprised, astounded, and amazed at what happenswith θ(0) = 3.1. This case is a nearly straight up pendulum, whichshould fall over, but as you can clearly see, the pendulum is now stablein the straight-up position. This is not a mistake, as you can discoverby examining the electric saber-saw demonstration at the front of theroom.

Page 68: computational physics 330 - Physics and Astronomy - Brigham

62 Computational Physics 330

(c) Analyze this situation more carefully by finding the effective potentialthat produces the right-hand side of the slow equation of motion,Eq. (12.14), i.e., find V (Θ) such that

−∂V /∂Θ=−ω20 sinΘ− b2ω2

2L2 sinΘcosΘ (12.15)

(integrate both sides of this equation to obtain V (θ)). Then plot thispotential from Θ = 0 to Θ = 2π for various values of b in the rangeb = 0 to b = .1 and notice what happens atΘ=π as b increases. Thenuse calculus to find the critical value of b at which the straight-uppendulum first becomes stable and use your code from part (b) toverify that this threshold value is correct.

These low frequency effective forces that arise from high-frequency non-lineareffects are called ponderomotive forces and they show up all the time in physicalproblems. This problem is just a small taste of a very large field.

Publication Quality Plots (Optional)

P12.2 (a) Read and work through Introduction to Matlab, Chapter 15. Type andexecute all of the material written in this kind of font.

(b) Produce a publication quality EPS plot of some fake data and a fakemodel produced by

x=0:pi/200:2*pi;

f=sin(x).*exp(-x)+0.01*sin(15*x);

data = f + 0.1*rand(1,length(x))-0.05;

Plot the data as red circles and the model as a blue line, and makeyour eps 16 cm wide and 8 cm tall. Make the range of the plot fromθ = 0 to θ = 6π and make sure the x-axis ticks are labeled correctly.This wide format is sometimes used when a figure need to span twocolumns in the printed article.

Import this EPS into a word processor and print it to verify that thesizing is correct. (Don’t resize it after importing.)

NOTE: Many word processors don’t render EPS files very well onscreen, so the graph may look bad when viewed on-screen. How-ever, when you print the document (or create a PDF of the document),the graph is rendered by the printer (or PDF viewer) and will look niceand sharp. In contrast, bitmap graphics look good on-screen but lookbad when printed (unless they have very high resolution).

Page 69: computational physics 330 - Physics and Astronomy - Brigham

Lab 13

Two Gravitating Bodies

Consider two masses interacting through Newton’s law of gravity: 1

m1r1 =− Gm1m2

|r1 − r2|3(r1 − r2) (13.1)

m2r2 =− Gm1m2

|r1 − r2|3(r2 − r1) (13.2)

There are components of the motion described by these equations: x1(t ), y1(t ),z1(t ), x1(t ), y1(t ), z1(t ), x2(t ), y2(t ), z2(t ), x2(t ), y2(t ), z2(t ).

P13.1 (a) Use the equations of motion above, plus x1 = vx1, etc., to obtain the12 first order differential equations for this system. Write them downon paper.

(b) Have Matlab solve this system of equations using G = 1, m1 = 1, m2 = 2and initial conditions

x1(0) = 1, x2(0) =−1y1(0) = 0.5, y2(0) =−0.3z1(0) =−0.3, z2(0) = 0.6vx1(0) = 0.65, vx2(0) =−0.45vy1(0) = 0.2, vy2(0) = 0.3vz1(0) = 0.1, vz2(0) =−0.3.

Run the solution from t = 0 to t = 50. After obtaining the solutionarrays interpolate them onto new arrays equally spaced in time (x1e,y1e, z1e, x2e, y2e,... with N=5*length(t)).

Now animate the motion of the two masses by using the plot3 com-mand. A nice way to do this animation is to use the arrays that areequally spaced in time, so that you can see the masses speed up asthey approach each other, and to plot the orbits in segments of 5,or so, data points. Using just one point makes the orbits appear assequences of dots, and using more points makes the plots be “jerky.”A loop that will do this kind of animation is shown below:

for n=5:4:N

plot3(x1e(n-4:n),y1e(n-4:n),z1e(n-4:n),'b-');

hold on

plot3(x2e(n-4:n),y2e(n-4:n),z2e(n-4:n),'r-');

axis equal

pause(.1)

end

hold off

1R. Baierlein, Newtonian Dynamics (McGraw Hill, New York, 1983), Chap. 5, and G. Fowles andG. Cassiday, Analytical Mechanics (Saunders, Fort Worth, 1999), Chap. 6.

63

Page 70: computational physics 330 - Physics and Astronomy - Brigham

64 Computational Physics 330

As your script runs you should see your masses doing an intricategravitational dance, and the final picture should look just like the onein Fig. 13.1 (after the appropriate rotation of your figure).

−4 −2 0

05

10−8

−6

−4

−2

0

y

Two Masses Orbiting and Drifting

x

z

Figure 13.1 Two masses interact-ing via the inverse-square law.

We are about to ask you to do some calculations with 3-dimensional vectorsand it will be easier if you turn your separate x, y , and z arrays into matricesinstead. For instance, the r1 vector would be a matrix with 3 columns and asmany rows as there were time steps in the output from ode45. The vectors for the3-dimensional positions and velocities of both particles can be defined like this:

r1=[x1,y1,z1];

r2=[x2,y2,z2];

v1=[vx1,vy1,vz1];

v2=[vx2,vy2,vz2];

Let’s also define versions of these vectors with the data equally spaced in time:

r1e=[x1e,y1e,z1e];

r2e=[x2e,y2e,z2e];

v1e=[vx1e,vy1e,vz1e];

v2e=[vx2e,vy2e,vz2e];

With them in this form the rest of this problem will be easy.

Center of Mass Coordinates

In physics we always seek the simplest description of the motion, which is why inclassical mechanics we trade in r1 and r2 for the center of mass position and therelative position of m1 with respect to m2:

R = m1r1 +m2r2

m1 +m2; r = r1 − r2 (13.3)

P13.2 (a) Use Matlab to make 3d plots of R and V = R for the case you just ranand show that their motion is very simple. Using the matrices we hadyou define above, you can define the vectors R, r, V, and v like this:

R=(m1*r1+m2*r2)/(m1+m2);

V=(m1*v1+m2*v2)/(m1+m2);

r=r1-r2;

v=v1-v2;

(equally spaced in time too:)

Re=(m1*r1e+m2*r2e)/(m1+m2);

Ve=(m1*v1e+m2*v2e)/(m1+m2);

re=r1e-r2e;

ve=v1e-v2e;

To make a 3-dimensional plot of these quantities use the command:

plot3(R(:,1),R(:,2),R(:,3))

Page 71: computational physics 330 - Physics and Astronomy - Brigham

Lab 13 Two Gravitating Bodies 65

Make sure you understand how the colon command works in thisexample.

(b) Make a 3d plot of the difference vector r and use the frame rotationtool on the figure frame to see that this vector seems to sweep out acurve that lies in one plane and looks like an ellipse.

(c) To see why the difference motion lies in a plane, compute the angularmomentum in the center of mass frame

L = m1(r1 −R)× (v1 −V)+m2(r2 −R)× (v2 −V) (13.4)

and show numerically that this vector is constant in time. Since youhave the vectors that appear on the right-hand side of this expressionfor L you can evaluate the angular momentum as a matrix (rows aretime, columns are x, y, z components):

L=m1*cross(r1-R,v1-V)+m2*cross(r2-R,v2-V);

And then you can plot each component of the angular momentum vs.time:

plot(t,L(:,1),t,L(:,2),t,L(:,3))

(d) Show graphically that L is perpendicular to both r1−R and r2−R (andhence to r1 − r2). To evaluate these two dot products using Matlab’sdot command you will need to make a slight change to the syntaxwe used above with the cross command. The dot command whenused with matrices needs to know whether we want to do the dotproduct along the row direction or the column direction. In this labthe rows label time, and the columns label x, y, z components. Sincewe want to do the dot product with the x, y, z components, we tell thedot product command to use the second, or column, index like this:

dot1=dot(r1-R,L,2)

dot2=dot(r2-R,L,2)

Do not panic when your plots of these two dot products look surpris-ing; check the scale on the left side of the plot. Note that this meansthat the planar motion you observed in the plot of r is simply a conse-quence of conservation of angular momentum (think about this anddiscuss it with your lab partner until you are convinced that it is true).

Kepler’s Laws

We are now going to use Matlab to verify Kepler’s laws. In Newton’s more preciseform, they are

Kepler’s First Law The difference vector r sweeps out an ellipse with body num-ber 2 at one focus. (Note that by definition r is the vector that points fromm2 to m1, so r = 0 is at the position of m2).

Page 72: computational physics 330 - Physics and Astronomy - Brigham

66 Computational Physics 330

Kepler’s Second Law An imaginary line drawn from m2 to m1 (the r vector)sweeps out equal areas in equal times.

Kepler’s Third Law The squares of the planetary periods are proportional tothe cubes of the semi-major axes, or in more modern (and more precise)language, the period T of the orbit is given by

T = πp2

µ1/2Gm1m2

(−E)3/2(13.5)

where µ is the reduced mass

µ= m1m2

m1 +m2(13.6)

and where E is the total energy in the center of mass frame:

E = µ

2|r|2 − Gm1m2

|r| (13.7)

(remember that r = r1 − r2 and that r = v = v1 −v2).

Before we begin verifying these laws, we need to simulate the solar systemthat Kepler studied. To do this, make m1 very small compared to m2, for examplem2 = 1 and m1 = 1e −8.

Also, you can save yourself a lot of trouble by changing the initial conditionsso that the motion lies only in the x y plane, and so that the ellipse is orientedsquarely in this plane. To keep the motion in the x y plane set all z positions andvelocities to zero. Then make the sun stationary by setting the other coordinatesand velocities of m2 to zero. Finally, give m1 simple initial conditions that willmake an elliptical orbit squarely oriented in the x y plane. (Go to the board anddraw some pictures; with a little imagination you will be able to see what theseinitial conditions are like).Note: You will need to be a little bit careful to make sure that the total energyis negative so that the orbits are confined. If your plots of the orbit look likeparabolas headed to infinity and beyond, start with less initial velocity.

OK, now we are ready to verify Kepler’s laws.

P13.3 (a) Verify Kepler’s first law.

You will need to remember that if the semi-major axis of the ellipse isa and if the semi-minor axis of the ellipse if b, then the distance fromthe center of the ellipse to a focus is f =

pa2 −b2.

To show that it is an ellipse first make sure that you are using initialconditions that make the orbit be squared up in the x y plane (i.e. havethe axes of your ellipse lined up with the x and y axes). When youhave an ellipse in the x y plane on your screen use hold on and theparametric form for an ellipse

x = a cos s y = b sin s s ∈ [0,2π]

Page 73: computational physics 330 - Physics and Astronomy - Brigham

Lab 13 Two Gravitating Bodies 67

to lay an ellipse over your orbit to see if they match. You can find thevalues of a and b from your x and y data, then shift the ellipse by thefocus distance to overlay the two ellipses.

Once you have a nice ellipse, change the power in the denominator ofthe force law from 3 to 3.1 to see what kinds of orbits power laws otherthan inverse square make. You should find that the orbit is still sort ofelliptical, but that the semi-major and semi-minor axes rotate; we callthis kind of motion “precession” and it looks like the figure below.

−1 −0.5 0 0.5 1−1

−0.5

0

0.5

1

x

y

Non−inverse Square Law

Figure 13.2 Precession of the orbit,non-inverse-square.

In general relativity the gravitational force law is not precisely inverse-square, so this kind of precession is expected to occur. Mercury’s orbithas a small precession of this kind (the famous “precession of theequinox of Mercury") which has been measured for centuries. WhenEinstein’s equations correctly predicted this precession it was a majortriumph for his theory of general relativity.

(b) Verify Kepler’s Second law.

This law is hard to verify numerically if the vector sweeps out a largearea per time interval. To make it easier make sure you have lots ofequally spaced time points along your orbit from part (a). Use a crossproduct to calculate successive areas using a triangle approximationand see if they are close to equal. Be sure to use your equally-spaced rarray re to do this calculation. As in part (a) it is good idea to look atthis data by plotting the small areas vs. time to see how constant theyare.

(c) Verify Kepler’s Third law.

To find the period look at a plot of x vs. t , or some other quantity thatvaries periodically during an orbit. Zoom in on the graph to find theperiod of the orbit.

To find E recall that energy is conserved, so you only need to eval-uate E at one point in time, which is easy to do by using the initialconditions.

You could find the period more precisely by using the methods dis-cussed in Introduction to Matlab, Sec. 13.4. If you have time, you mightwant to read through this section to see how Matlab’s event-finderworks.

Page 74: computational physics 330 - Physics and Astronomy - Brigham
Page 75: computational physics 330 - Physics and Astronomy - Brigham

Lab 14

Hysteresis in Nonlinear Oscillators

The topic for this lab is hysteresis in nonlinear oscillators, an interesting andimportant effect. If you want to read more about this topic, see below. 1

Qualitative Analysis

Consider a damped-driven harmonic oscillator whose spring becomes weaker asthe amplitude increases according to the equation of motion

x =−2γx +F (x)+ A cosωt , (14.1)

where the restoring force F (x) is given by

F (x) =−2

3

tanh(3x/2)

cosh2 (3x/2), (14.2)

and where both linear damping (−2γx) and a sinusoidal driving force (A cosωt )have been included. Note that the particle mass has been set to m = 1. So youdon’t panic at the ugliness of F (x), let’s plot it so you can see that it’s nice andregular.

P14.1 Plot both the force F (x) and the potential energy function U (x) associatedwith this oscillator:

F (x) =−∂U /∂x (14.3)

between x =−3 and x = 3.

Look at the potential energy plot now and notice that the bottom of the welllooks pretty parabolic. This means that a low energy particle feels a force thatis almost the same as the simple linear restoring force of the simple harmonicoscillator.

P14.2 To clearly understand this point, expand F (x) in a Taylor series in smallx up to 7th order and show that the natural frequency of oscillation for aparticle with small displacement x is ω0 = 1.

HINT: Write down the equation of a simple harmonic oscillator and com-pare it to your expansion.

1R. Baierlein, Newtonian Dynamics (McGraw Hill, New York, 1983), p. 81-88, and G. Fowles andG. Cassiday, Analytical Mechanics (Saunders, Fort Worth, 1999), p. 108-110.

69

Page 76: computational physics 330 - Physics and Astronomy - Brigham

70 Computational Physics 330

But if the particle were to gain more energy and move higher in the well, then itwould be sampling the potential energy curve where it departs from a parabolicshape by opening out. This means that over part of the particle’s orbit it feels lessrestoring force than the simple linear force F =−x (see your plot of F (x)), and lessrestoring force means a lower oscillation frequency for the particle. This nonlineareffect, by which natural frequency becomes a function of oscillation amplitude(which we have seen before with the pendulum), has strange consequences forthe resonance curve of this oscillator.

At the beginning of the course you made plots of the amplitude of a driven-damped harmonic oscillator and saw that when the damping was large there wasonly a small bump in the plot of the oscillation amplitude vs. driving frequency ω.But as the damping was decreased this bump became more and more peaked,until finally a sharp resonance curve was observed. In this lab we will study thesame kind of resonance behavior for this nonlinear oscillator, but we will findthat the resonance curves develop a very odd twist. To follow this story to itsconclusion will require quite a bit of mathematics and computation, but beforewe tackle the technical details let’s try to think about the problem qualitativelyfirst.

To understand why nonlinearity makes so much difference in resonance, let’simagine two different scenarios, represented in Fig. 14.1

Figure 14.1 A rough sketch of anonlinear resonance curve.

(i) Using a relatively small driving force and weak damping let’s imagine start-ing at small driving frequency ω and then gradually increasing it towardresonance. At first the oscillator amplitude is low enough that simple har-monic oscillator behavior is observed, but as resonance is approached andthe amplitude increases the resonant frequency shifts downward. Hencewe might expect the resonance peak to occur at a lower value of ω than thevalue of ω0 = 1 that you calculated earlier in this section. This situation isindicated by the lower curve in Fig. 14.1.

(ii) Again using small driving force A and weak damping, let’s imagine startingat high frequency and sweeping ω downward toward resonance. At first theamplitude is small and harmonic oscillator behavior is observed. But as weapproach resonance and the amplitude increases the resonant frequencydecreases, moving further away from us. We keep decreasing ω, the ampli-tude continues to grow because we are still approaching resonance, andthe resonant frequency decreases still further. As this process continueswe find ourselves at a frequency below ω0 = 1, and then even below thefrequency where the early resonance occurred in scenario (i) (as shown bythe upper curve in Fig. 14.1) but with the amplitude still high because weare continuing to chase the decreasing resonance frequency.

But this means that at some values of the driving frequency there are twopossible oscillation amplitudes, as indicated by the dashed line in Figure 14.1. Thecurves in this figure look completely different from the ordinary resonance curves

Page 77: computational physics 330 - Physics and Astronomy - Brigham

Lab 14 Hysteresis in Nonlinear Oscillators 71

of the simple harmonic oscillator and the goal of this lab is to use computation tofigure out how the upper and lower branches in Fig. 14.1 are related.

Mathematica Analysis

As a first attempt to understand the behavior of Fig. 14.1 it will be helpful to dosome analysis with Mathematica. This analysis will only be approximate, but willhelp us see how the resonance curve might behave. The first approximation isto assume that x is small enough that it makes sense to only keep the first twonon-zero terms in the Taylor expansion of F (x) that you did in P14.2. Under thisapproximation, the force given in Eq. (14.2) is

F (x) ≈−x +3x3 .

The second approximation is to ignore the damping term in Eq. (14.1), so thatour equation of motion becomes

x =−x +3x3 + A cosωt . (14.4)

Since we are interested in the driven response of this system, and since thedriving force is proportional to cosωt , we certainly expect the response x(t) toalso contain a term like cosωt . But if x(t) ∝ cosωt , then because of the cubicterm in the equation of motion its solution probably also involves a term likecos3ωt . And since cos3ωt = 3

4 cosωt + 14 cos3ωt , we then expect x(t) to involve

cos3ωt as well. Let’s use these two suspected ingredients to approximately predictthe amplitude of this steady oscillation. Assume that x(t ) is of the form

x(t ) = c1 cosωt + c3 cos3ωt . (14.5)

P14.3 (a) Use Mathematica to substitute this form for x(t ) into Eq. (14.4). Turnpowers of cosine into terms containing cos(nωt), n = 1,3,5, ..., andthen collect the terms that are proportional to cosωt and cos(3ωt).We will ignore all of the higher order harmonics, hoping that they aresmall.

You will find that the collected form of the equation looks like this:

(· · · )cos(ωt )+ (· · · )cos(3ωt )+·· · = 0 .

Since cos(ωt ) and cos(3ωt ) are independent functions of time theircoefficients (· · · ). must separately be equal to zero, giving us two messyequations to determine the coefficients c1 and c3 in terms of A and ω.

(b) Assume that c1 is small and that c3 is even smaller to obtain from thecos3ωt component of the equation a simple approximate expressionfor c3 in terms of c1 and ω. In doing so make sure you only keep theterms that contain c3 as a linear factor (drop any terms containingpowers of c3) and when you are considering what to do with two terms

Page 78: computational physics 330 - Physics and Astronomy - Brigham

72 Computational Physics 330

containing c31 and c2

1c3, keep c31 and drop c2

1c3 because we expectc3 ¿ c1. You should find

c3 =3c3

1/4

1−9ω2 (14.6)

Under what conditions is c3 not small as we assumed? In particular,what value of ω totally invalidates this assumption? This special valueof ω will make an appearance later in this lab.

(c) Now use this approximation for c3 in the cosωt equation to obtain anapproximate cubic equation for c1 involving ω and A by eliminatingthe higher order terms for c1. Surprisingly, you will find that c3 playsno role in the approximate equation for c1 which is

c1 −ω2c1 − 9

4c3

1 = A (14.7)

(d) Have Mathematica solve for the three roots of this equation with A =0.136 and put the formulas for the three values of c1 in the variabless1, s2, and s3.2

(e) Now make two separate plots of s1, s2, s3:

(i) plot |Re(c1)| from ω= 0..2 (all three roots on the same plot) and

(ii) plot Im(c1) from ω = 0..2 (again, put all three roots on the sameplot.

The second imaginary plot is important because if c1 has an imagi-nary part, then this root has no physical significance in our problem,meaning that the corresponding parts of the curves in the real plot (i)should be ignored. (And the reason that we plot the absolute value|Re(c1)| is that c1 is an amplitude, so we don’t want to distinguishbetween positive and negative values).

(f) Now that you know which roots are physical, stare at the plot of theabsolute value of |c1| and notice that for driving frequency ω belowabout 0.6 there are three real roots for c1, but beyond 0.6 there is onlyone.

This change from one solution to three is the effect that makes this oscillatorso interesting, and gives us a hint about how to complete Fig. 14.1. To see why,consider the following three scenarios for starting the oscillator at some drivingfrequency ω and then slowly changing it using the c1 curves you have just made.

(i) Suppose that we start with a large driving frequency, then slowly decreaseω. Above 0.6 there is a single amplitude c1, and as the frequency decreases

2Maple can solve a cubic like this, but the answers look horrible, so just assign each one to a sep-arate variable like this: sol:=solve(eq,c1): s1:=sol[1]: s2:=sol[2]: s3:=sol[3]:

(use colons at the end instead of semicolons so you don’t have to look at pages and pages ofblue output).

Page 79: computational physics 330 - Physics and Astronomy - Brigham

Lab 14 Hysteresis in Nonlinear Oscillators 73

the curve predicts that c1 should increase. When we reach 0.6 there arethree possible solutions, but if we only make slow changes in the frequency,perhaps we will stay on the upper branch and c1 will continue to increase.

(ii) Suppose that we start at low driving frequency and slowly increaseω toward0.6. The amplitude c1 will increase slowly along the lower branch, but soonthe amplitude begins to increase rapidly because of the “early resonance”effect discussed in (i), and as we pass 0.6 the lower branch ceases to existand the oscillator is forced to jump up to the upper branch, after which itdecreases in amplitude as ω increases.

(iii) And what about the curve which is intermediate between high and lowamplitude between ω = 0 and ω = 0.6? As you will see later, this branchis unstable and an oscillator that tries to live here will quickly either dropdown to the lower branch or jump up to the upper one. And as you will alsosee later, if damping is added the two upper curves no longer both continueon to ω= 0 as happens in your Mathematica curves. Instead they connecttogether, as you can see on the picture that graces the course web page(the red outlines are resonance curves for various values of the dampingconstant γ) or in Fig. 14.2 below. The surprising result is that the nonlinearresonance curves are like standard harmonic oscillator resonance curvesthat have been pushed over, like a flopped-over witches hat. During therest of this lab you will be writing Matlab code to make such curves.

Figure 14.2

The important nonlinear effect in this behavior is that at frequencies below 0.6you can’t tell what the driven amplitude of the oscillator will be without knowingthe details of how the driving frequency has been changing. This effect is calledhysteresis, the Greek word for memory. This word is appropriate here because thestate of the oscillator doesn’t just depend on the current value of ω, but also onwhat ω used to be: the system remembers what path it has been following as ωhas been changing.

Matlab Calculation

As you were dropping terms in the previous section with wild abandon you mayhave wondered if the analysis was going to be any good. Well, the point of havinga computer is to do difficult problems right, so let’s see if we can coax Matlab intofinding the correct steady response of the oscillator to the driving force, includingboth the full nonlinear form of the force and damping too.

The straightforward way to see how the oscillator responds is to give it someinitial conditions x(0), v(0) and run it for a long time to see which final steadystate it settles into. Unfortunately, doing it this way takes a long time, and it alsowon’t allow us to explore the middle unstable branch of the resonance curve.

A better way to do this calculation is to notice that if the oscillator is to respondto the drive in a steady way then x(t ) and v(t ) of the oscillator must both be peri-odic with the same period as the drive: T = 2π/ω. So for each driving frequency ω

Page 80: computational physics 330 - Physics and Astronomy - Brigham

74 Computational Physics 330

there must be a set of initial conditions x(0, v(0) that would produce the perfectfinal steady state. We could imagine looking for this special state by repeatedlychoosing initial values for x(0) and v(0), solving the differential equation from 0to T , and then checking to see if x(T ) and v(T ) match their initial values. If theydon’t we could keep adjusting x(0), v(0) until they do. If we’re lucky, solving thedifferential equation over the short interval [0,T ] will make up for the initial valuesearching we do, and make the calculation run faster than just waiting for steadystate to happen. But to be lucky, we will need a clever way of quickly finding thecorrect initial conditions, and Matlab’s minimizer fminsearch turns out to dothe job.

This will be the most involved programming project of the semester, so wewill try to guide you through it step by step. You will not finish this lab today, butdon’t panic–we will continue this work into next week.

OK, it’s time to write your own Matlab code to make a figure like Fig. 14.2You will have to write a main script and two function M-files, and they are a littleinvolved. The instructions that follow are a kit to solve this problem. We won’t tellyou everything you need to know, but most of it is here. As you go along you willbe building a chain of 5 M-files and Matlab commands that call each other, likethis:

lab13.m -> fminsearch -> leastsq13.m -> ode45 -> rhs13.m

Keep this chain in mind as you work through the rest of this lab.

P14.4 Write a main script called lab13.m that starts ω at ω1 and ends it at ω2

taking N steps along the way. This is how we will track the response ofthe oscillator as we scan ω through resonance going either up or downin frequency. This script, which we call lab13.m, should do the followingthings:

(a) Declare the driving frequency ω, the driving amplitude A, and thedamping constant γ as global variables. After they are declared givethem values A = 0.136 and γ= 0.2. Also declare the variable S to beglobal (you will see why later).

(b) Use input commands to enter values ω1, ω2 to define the drivingfrequency scan interval, and also use input to enter N , the number ofscan points. Then calculate the step size in the scan h = (ω2 −ω1)/Nand use it to define an array ofω-values called wscan that will be usedin the scan.

(c) Use input commands to enter initial guesses for x(0) and v(0).

(d) Write a loop that steps through the w array of ω values and asks Mat-lab’s minimizing utility fminsearch to refine the initial guesses forx(0) and v(0) to find the correct initial conditions to make x(t) andv(t ) be periodic with period T = 2π/ω, the same as the period of thedriving force. An example of what your loop should look like is givenbelow.

Page 81: computational physics 330 - Physics and Astronomy - Brigham

Lab 14 Hysteresis in Nonlinear Oscillators 75

Listing 14.1 (loop.m)

guess=[x0;v0];

for j=1:length(wscan)

w=wscan(j) % no semicolon so w will print on the screen

T=2*pi/w;

optionfmin=optimset('TolX',1e-6);

answer=fminsearch(@leastsq13,guess,optionfmin) % no semicolon so that

% the correct (x0,v0)

% will be on the screen

S % print S, the minimum error from fminsearch, on the screen

% now that fminsearch has found initial conditions for

% a periodic orbit, calculate the orbit and find its

% amplitude Amp(j) by finding the maximum value of x(t)

% over a period.

optionode=odeset('RelTol',1e-6);

[t,yode]=ode45(@rhs13,[0,T],answer,optionode);

x=yode(:,1);v=yode(:,2);

% save the amplitude at each step of the scan

Amp(j)=max(x);

% plot the solution to make sure it is periodic

plot(t,x,'b-',t,v,'r-')

title(sprintf('\\omega = %g ',w));

xlabel('t');ylabel('x(t), v(t)');

pause(.1)

% use the answer we just found as the guess to pass into fminsearch

% when we go back up for the next value of w

guess=answer;

end

% After the scan is finished plot amplitude vs. frequency

plot(wscan,Amp)

The code above is just a bare-bones version. As you use it you will encountervarious problems which you will want to fix by adding new code to the loop above.

You will notice that in the loop in (d) fminsearch needs an M-file leastsq13and that ode45 needs an M-file rhs13. Let’s start with leastsq13. You may recallthat fminsearch is a Matlab routine that varies a set of parameters until it finds aspecial combination of them that minimizes a scalar function of the parameters.In our problem we want to choose a scalar function that is a minimum whenthe orbit returned by ode45 is periodic, i.e., the orbit satisfies x(T )−x(0) = 0 andv(T )− v(0) = 0. A scalar function (chosen to have units of velocity) that has aminimum when these conditions are satisfied is

S =ω2(x(T )−x(0))2 + (v(T )− v(0))2

and this is the quantity that we want leastsq13 to calculate so fminsearch canminimize it.

Page 82: computational physics 330 - Physics and Astronomy - Brigham

76 Computational Physics 330

P14.5 (a) Write leastsq13.m following the pattern in Listing 14.2. We have leftsome blanks for you to fill in, indicated by the dots.

(b) Finally, create the function rhs13 called by both the main script andby leastsq13. This is just the usual right-hand side function used byode45 and should look Listing 14.3. Make sure you use the force inEq. (14.2) instead of the simple approximate force F ≈−x +3x3.

(c) Now it is time to debug and test the code we have written so far.Use A = 0.136 and γ = 0.2. To test the code, set ω1 = 1.8, ω2 = 2,and N = 5 so that we are working well above the resonance nearω= 1. At this driving frequency the amplitude should be low and x(t )should be 180 degrees out of phase with the driving force, so we expectsomething like x(0) =−A/ω2 and v(0) = 0 to give a periodic solution.Run and repeatedly debug the code you have written until you obtaina reasonable result. As a numerical check, with γ= 0.2 and ω= 2 thecorrect initial values are (x0, v0) = (−0.0423,0.0225).

Listing 14.2 (leastsq13.m)

function S=leastsq13(guess)

global A w gamma S;

T=2*pi/w;

% fminsearch will give this function various initial conditions

% [x0;v0] through the input variable guess. This function's

% job is to solve the differential equation with these proposed

% initial conditions and return a value for S so that fminsearch

% can know how close it is to choosing [x0;v0] that make S be

% a minimum. The differential equation is to be solved over time

% interval [0,T] with relative tolerance 1e-6. After the solve,

% which is of the form [t,yode]=..., unpack yode into x and v.

.

. write your own code here to call ode45

.

% now subtract the final and initial values to build S

% note that x(end) is Matlab syntax for the last element of x.

S=w^2*(x(end)-x(1))^2+(v(end)-v(1))^2;

return

Listing 14.3 (rhs.m)

function F=rhs13(t,y)

global A w gamma;

F=zeros(length(y),1);

% load the column vector with the derivatives of x and v

x=y(1);v=y(2);

F(1)=v;

F(2)=....(put the differential equation here)

return

Page 83: computational physics 330 - Physics and Astronomy - Brigham

Lab 14 Hysteresis in Nonlinear Oscillators 77

Now we are going to use this set of codes to explore the true hysteresis diagramwhich we approximated in the Mathematica analysis.Important: Use A = 0.136 throughout the rest of this lab.

P14.6 (a) Set γ= 0.015 and do a scan from ω1 = .1 to ω2 = .4. Use N = 80. Nowthat you are at low driving frequency using x(0) =−A/ω2 is a very badidea. Use a small value instead, like x(0) = 0.15. N = 80 should be alarge enough value that you can see the predicted resonant behaviorat ω= 1/3, as well as another small resonance at ω= 1/5. This secondresonance is expected because of the appearance of cos5ωt amongthe higher-order terms we neglected earlier. Other terms like cos7ωt ,cos9ωt , etc. were also neglected. Can you see something at ω= 1/7?At ω= 1/9? Why are they harder to see, and why are the resonancesshifted slightly from these values? (Zoom in on the plot to see them).

(b) Now run your loop from low frequency at ω1 = 0.2 up to high fre-quency at ω2 = 2 with the following value for the damping constant:γ= 0.2. Use N = 40. You will find that with this damping value there isno hysteresis, although the slightly bent-over shape of the resonancecurve gives a hint of what is about to happen.

Now for the main event.

P14.7 Set the damping constant to γ= 0.15 and run your loop for 5 different setsof values of ω1 and ω2, as follows.

(a) Use ω1 = 2 and ω2 = 0.7 to follow the upper curve down in frequencyfrom the low-amplitude states at high frequency. Use N = 30. Makesure that ω, (x0, v0), and S are printing on the screen so that you canscroll back up if you need to see them.

When your scan has finished, save wscan and Amp to disk so that lateryou can read all of the scan results back in and overlay their plotsto make your own version of Fig. 14.2. For instance, if you wantedthe results of this first scan (both amplitude and angular frequency)stored in a file named scan1.mat, you would type this at the Mat-lab command prompt (or put this code at the bottom of your lab13script:)

save scan1 Amp wscan

You will encounter a problem as you do this scan: fminsearch willsometimes lie to you by returning reasonable amplitudes when thevalue of S is too large to correspond to a solution. The problem isthat fminsearch is a minimizer, not a solver, so when it finds a localminimum in parameter space, it thinks it has done its job properlyand it quits. To take care of this problem, after the call to fminsearch

in lab13.m test the value of S to see if it is too big. If S is larger than

Page 84: computational physics 330 - Physics and Astronomy - Brigham

78 Computational Physics 330

about 10−8 the solution has failed and you should break out of thescan loop using the break command.

Unfortunately, breaking out will now cause another problem: thefrequency scan array wscan and the corresponding amplitude arrayAmp do not have the same length. A simple way to fix this problem isto redefine wscan to be the right length to match Amp after the bottomof the loop, like this:

wscan=wscan(1:length(Amp));

Another problem you will encounter is that it may be hard to stay onthe upper curve because your code will want to jump down to thelower one before very much hysteresis is observed. This is caused bynot giving fminsearch a sufficiently accurate initial guess. You canfix this by using linear extrapolation, like this:

Before the call to fminsearch set an old answer variable equal to thelast answer (which contains refined values of [x0;v0]) so that it willbe remembered before a new answer is found:

oldanswer=answer;

Then at the bottom of the loop replace the code

guess=answer

with linear extrapolation:

guess=2*answer-oldanswer

And finally, just above the top of the scanning loop initialize theanswer variable so that extrapolation will work the first time by chang-ing the line

guess=[x0;v0];

to

guess=[x0;v0];

answer=guess;

This will only work well if you supply a pretty good initial guess for(x0, v0).

(b) Now use ω1 = 0.7 and ω2 = 0.55 to finish the upper curve. Use N = 30.To start the code you will need to scroll up and see what (x0, v0) werein your first scan when you got to ω= 0.7. Remember to save wscanand Amp to disk with a different file name than you used in (i).

(c) Now use ω1 = 0.2 and ω2 = 0.7 to follow the lower curve from lowfrequency up to the point where it curves up and jumps up to theupper branch. Use N = 30. Does this upward jump occur anywherenear the value predicted by the Mathematica plots you made earlier?Does the jump occur at a higher value of ω than the last good valueon the upper curve in (ii)? If it does, then you have achieved hystere-sis. Congratulations. Remember to save wscan and Amp to disk withdifferent file names than you used in (i) and (ii).

Page 85: computational physics 330 - Physics and Astronomy - Brigham

Lab 14 Hysteresis in Nonlinear Oscillators 79

(d) To explore the middle branch choose ω1 = 0.6, ω2 = 0.55, and use(x0, v0) = (0.35,0.31) with N = 20. This will produce the left half of themiddle branch.

(e) Now choose ω1 = 0.6, ω2 = 0.7, and use (x0, v0) = (0.35,0.31) withN = 20. This will produce the right half of the middle branch, and isthe last of the scans.

(f) Make the complete picture of the resonance curve by writing a scriptthat overlays the results of all 5 scans on the same figure using theload commands given in (a) above.

To do this you will need to load each scan and plot its results. Readingthem back in is a little tricky because Matlab not only saves the datain its .mat files, but it also stores the original name of the variableand restores it when you read it back in. For example, if you use thecommand

load scan1

then the amplitude and angular frequency values for scan 1 would bestored in the variable names Amp and wscan. If you then load scan2,its values for Amp and wscan will replace those for scan1. So the scriptto overlay all of the plots should be written like this:

load scan1

plot(wscan,Amp,'b*') % plot Amp vs. wscan from data set 1

hold on

load scan2

plot(wscan,Amp,'g*') % plot Amp vs. wscan from data set 2

.

.

.

Look up save and load in online help to see more details.

(g) Modify your code just slightly to study the stability of the oscilla-tor states you found in this problem. In lab13.m change the code[0,T] in the line that calls ode45 to [0,100*T] so that we can see thelong-time behavior of the oscillator state found by fminsearch. Alsochange the line pause(.1) to pause so that lab13.m won’t move onto the next point in the scan without your permission.

(i) Start a scan with ω1 = 0.3, ω2 set to anything else, and N = 2. Wedon’t care about ω2 because we will only be looking at the first point,ω=ω1. When the plots of x(t ) and v(t ) appear examine them carefullyand decide whether this oscillator state on the lower curve is stableor unstable. Then use Ctrl-c to kill this run and move on to the nextone.

(ii) Now start a scan withω1 = 1 and see if this state on the upper curveis stable or unstable.

(iii) Finally, start a scan with ω1 = 0.6 using (x0, v0) = (0.35,0.31) anddecide if this state is stable or unstable. You should find that it is

Page 86: computational physics 330 - Physics and Astronomy - Brigham

80 Computational Physics 330

unstable, but that the instability saturates by settling into a state oneither the lower curve or the upper curve, both of which are stable. Ifyou jumped up to the upper curve, modify the initial conditions in theline in lab13.m that calls ode45 from answer to 0.999999*answer

and run it again. Or if you jumped down, use the factor 1.000001instead. You should find that whether it jumps up or down dependsvery sensitively on the initial conditions, so if we were experimentallystudying a system with this behavior we would probably not evenknow that there was a middle branch.

Well, that’s it. You have now reproduced the bent-over resonance curve withhysteresis sketched in Fig. 14.2 and have found that the upper and lower branchesare stable, but that the middle branch is unstable. And you have also found thatwhen the damping is small there are small sub-resonances at ω=ω0/3, ω=ω0/5,etc.

Page 87: computational physics 330 - Physics and Astronomy - Brigham

Index

Amplitude, 28Attractor, 48

Baseball with air, 2Bessel function zeros, 57Butterfly effect, 50

Chaos, 47Coupled oscillators, 53critical damping, 27

Differential equations with Matlab, 47Dynamical chaos, 47, 49

Entrainment, 48, 51, 56Euler’s constant, 19

FFT, 36Fibonacci numbers, 52Fourier transform, 36Fractal curve, 52

Gravitating bodies, 63

harmonic oscilator, 25High-frequency driving forces, 61Hysteresis, 69

Integrals, numerical, 15Intermittency, 50

Kepler’s laws, 65

Limit cycle, 48

Nonlinear damped driven oscillator,69

Parametric oscillator, 39Pendulum, 31

Pendulum period, 31Pendulum, driven, 33Period-doubling route to chaos, 51Phase shift, 28Phase space, 11Ponderomotive forces, 62Pumping a swing, 39

resonance curve, 29Roundoff, 16

Simple harmonic oscillator, 28Strange attractor, 48

Zeros, Bessel functions, 57

81