89
Dickinson College Dickinson Scholar VPython for Introductory Mechanics 2019 VPython for Introductory Mechanics: Complete Version Windsor A. Morgan Dickinson College Lars Q. English Dickinson College Follow this and additional works at: hps://scholar.dickinson.edu/vpythonphysics Part of the Astrophysics and Astronomy Commons , Curriculum and Instruction Commons , Numerical Analysis and Computation Commons , Physics Commons , and the Science and Mathematics Education Commons is Book is brought to you for free and open access by Dickinson Scholar. It has been accepted for inclusion in VPython for Introductory Mechanics by an authorized administrator of Dickinson Scholar. For more information, please contact [email protected]. Recommended Citation Morgan, Windsor A. and English, Lars Q., "VPython for Introductory Mechanics: Complete Version" (2019). VPython for Introductory Mechanics. 1. hps://scholar.dickinson.edu/vpythonphysics/1

VPython for Introductory Mechanics: Complete Version

  • Upload
    others

  • View
    29

  • Download
    2

Embed Size (px)

Citation preview

Page 1: VPython for Introductory Mechanics: Complete Version

Dickinson CollegeDickinson Scholar

VPython for Introductory Mechanics

2019

VPython for Introductory Mechanics: CompleteVersionWindsor A. MorganDickinson College

Lars Q. EnglishDickinson College

Follow this and additional works at: https://scholar.dickinson.edu/vpythonphysicsPart of the Astrophysics and Astronomy Commons, Curriculum and Instruction Commons,

Numerical Analysis and Computation Commons, Physics Commons, and the Science andMathematics Education Commons

This Book is brought to you for free and open access by Dickinson Scholar. It has been accepted for inclusion in VPython for Introductory Mechanicsby an authorized administrator of Dickinson Scholar. For more information, please contact [email protected].

Recommended CitationMorgan, Windsor A. and English, Lars Q., "VPython for Introductory Mechanics: Complete Version" (2019). VPython for IntroductoryMechanics. 1.https://scholar.dickinson.edu/vpythonphysics/1

Page 2: VPython for Introductory Mechanics: Complete Version

VPython for IntroductoryMechanics

Incorporating numerical simulationsin the introductory physics

curriculum

W.A. Morgan and L.Q. EnglishDepartment of Physics and Astronomy

Dickinson College

Page 3: VPython for Introductory Mechanics: Complete Version

© 2019 W.A. Morgan and L.Q. English, Carlisle, PA 17013All Rights Reserved.

https://scholar.dickinson.edu/vpythonphysics/

For more information about permission to reproduce selectionsfrom this book, write to [email protected].

On the front cover: the large photograph is of Melba Roy Mouton.She calculated artificial satellite orbits as a Head Computer

Programmer for NASA.

Left Cover Image source: NASA on the CommonsRight Cover Image source: https://pxhere.com/en/photo/1199802

Page 4: VPython for Introductory Mechanics: Complete Version
Page 5: VPython for Introductory Mechanics: Complete Version

Contents

1 Introduction 1

2 Getting Started with VPython 52.1 “Hello.” . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Box – Your First Shape . . . . . . . . . . . . . . . . 82.3 Another shape . . . . . . . . . . . . . . . . . . . . . 112.4 Comments . . . . . . . . . . . . . . . . . . . . . . . 11

3 Moving Objects Using Formulas 133.1 Motion of a Ball with Constant Velocity . . . . . . . 133.2 Motion of a ball with constant velocity with a plot

of position vs. time . . . . . . . . . . . . . . . . . . 143.3 Motion of a Ball Being Dropped from Rest Near the

Surface of the Earth . . . . . . . . . . . . . . . . . . 163.4 Stop and Go . . . . . . . . . . . . . . . . . . . . . . 173.5 Motion of a Planet . . . . . . . . . . . . . . . . . . . 18

4 A First Look at Simulating Motion 214.1 The Physics . . . . . . . . . . . . . . . . . . . . . . . 214.2 The Basic Code . . . . . . . . . . . . . . . . . . . . . 234.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 25

5 Visualizing Projectile Motion 275.1 The Physics . . . . . . . . . . . . . . . . . . . . . . . 275.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 28

5.2.1 Projectile over Flat Ground . . . . . . . . . 285.2.2 Projectile over Sloping Ground . . . . . . . 305.2.3 Projectile Striking a Target . . . . . . . . . . 305.2.4 Mystery Code . . . . . . . . . . . . . . . . . 31

6 Simulating Central-Force Problems 336.1 Stating the general problem and a possible line of

attack . . . . . . . . . . . . . . . . . . . . . . . . . . 336.2 A first example: The mass-spring problem . . . . . 36

Page 6: VPython for Introductory Mechanics: Complete Version

6.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 376.4 A second example: Projectile motion with air drag . 386.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 426.6 Third Example: Trajectories of Planets and Comets 436.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 45

7 Conservation of Momentum and Energy 477.1 A binary-star system . . . . . . . . . . . . . . . . . 477.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 517.3 Energy in the Spring-Mass System . . . . . . . . . . 527.4 Simulating the Rutherford experiment . . . . . . . . 537.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 56

8 Rotational Motion, Torque, and Angular Momentum 598.1 The Physics . . . . . . . . . . . . . . . . . . . . . . . 598.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 61

9 Two Capstone Projects 639.1 The Gravitational “Slingshot” . . . . . . . . . . . . . 63

9.1.1 The Physics . . . . . . . . . . . . . . . . . . 649.1.2 The Code . . . . . . . . . . . . . . . . . . . 679.1.3 Exercises . . . . . . . . . . . . . . . . . . . . 69

9.2 Asteroid near a Binary Star System - Chaotic orbits,or the “Three-Body Problem” . . . . . . . . . . . . . 709.2.1 Modifying a previous code . . . . . . . . . . 709.2.2 Exercises . . . . . . . . . . . . . . . . . . . . 73

10 Conclusion 75

Bibliography 77

About Authors 79

Page 7: VPython for Introductory Mechanics: Complete Version
Page 8: VPython for Introductory Mechanics: Complete Version

Preface

Many physics departments nationally and internationally havemoved to incorporate more computation into their curriculum. Inmany cases this is accomplished by offering an upper-level electivein computational physics. Frequently, computational exercises arealso incorporated in upper-level course work. Less often do we seesubstantial integration of coding in the first semester of physics.One exception is the Matter and Interactions curriculum developedat North Carolina State University.1

In this book, we describe a series of group exercises that we in-corporated into our first course for majors. The calculus-based in-troductory sequence at Dickinson College is taught in the Work-shop Physics mode which emphasizes inquiry-based exploration ingroups. Students work through exercises in groups of four, andthese mostly involve guided observations, measurements and exper-iments. In the fall semester of 2018, we started supplementing thesewith numerical projects, and this book grew out of that experience.

In the following chapters, we describe a series of computational exer-cises that can be easily woven into a project-centered course format.Alternatively, these exercises could also be included into the labora-tory part in a more traditional course. The sequence of topics wasmeant to follow a typical calculus-based intro-mechanics course, aswell as an Advanced Placement Physics high school class. (It doesnot, however, mesh well with alternative paradigms, like the energy-first approach.) For instance, we start with graphing motion usingthe kinematics equations, then move on to projectile motion, beforedelving into dynamics and the simulation of motion using physicallaw. The next-to-last chapter is an exploration of rotational motion,torque and angular momentum conservation, topics usually at theend of a typical course. The last chapter considers the “real-world”

1R. Chabay, B. Sherwood, Matter and Interactions (John Wiley & Sons, 2015)

Page 9: VPython for Introductory Mechanics: Complete Version

example of gravitational assist in space travel.

One important precondition for such an endeavor is that the pro-gramming language not get in the way of the physics. For us, it wasnot very important for students to become proficient in coding. Infact, we chose to provide the students with a scaffold by giving theman initial template for almost all exercises, and students were thenasked to modify the code to complete the activities. In the samespirit, we tried to keep the code we gave students as short as possi-ble, while encouraging them to embellish as they saw fit.

We chose VPython for a number of reasons. First, it is convenientthat it lives online. Nothing has to be installed locally. Secondly, itswell-known strengths in 3D visual rendering is obviously a majorbenefit in a first course in classical mechanics. Finally, its basis inthe Python programming language allows students to get some earlyexposure to a language that is becoming ever more widely used inscientific computation.

L.Q. English and W.A. MorganCarlisle, Pennsylvania, August 2019

Page 10: VPython for Introductory Mechanics: Complete Version

Introduction

This book is intended to supplement the course materials of a first-semester introductory course in physics by adding a computationaldimension into the course content through the use of VPython - a“visual” extension of the Python programming language that incor-porates 3D animation and vector math. The book is not designed toreplace the regular course textbook. Since it is intended to be used inconjunction with other material presented in the course, one of thegoals was to make its integration into the course flow as seamlessas possible. To this end, we have organized the topics and exercisesso that they should more or less follow the traditional sequencingof topics encountered in most introductory mechanics courses.

The exact order of topics was chosen to enable its easy integrationinto our Workshop Physics curriculum.1 While the pedagogical ap-proach, format and presentation of Workshop Physics is very differ-ent from the more standard lecture-based course, its content selec-tion is fairly conventional. Thus, we believe that this presentationshould also work well in conjunction with a more traditional intro-ductory mechanics course (either at the senior high-school or first-year college level). Furthermore, swapping neighboring chapters oromitting certain sections should create only minimal disruption.

Having said that, introducing computation in the first semester doesallow for some curricular innovation, such as in the form of inclu-sion of types of problems that are not typically encountered other-wise. In particular, it allows students to examine problems that haveno closed-form analytical solutions, to engage in more creative andopen-ended problems,2 and to practice physical modeling. One ex-ample we include in this book has to do with the law of universal1Workshop Physics was developed at Dickinson College, principally by P. Laws, as an

inquiry-based, active-learning curriculum for introductory physics2E.F. Redish and J.M. Wilson, “Student programming in the introductory physics course”,Am. J. Phys. 61, 222 (1993).

Page 11: VPython for Introductory Mechanics: Complete Version

2 Chapter 1 Introduction

gravitation. After a sequence of exercises where students discoverKeplerian orbits, we ask them to explore what would happen to plan-etary orbits if gravity were instead a “1/r” kind of force. Such aquestion would be quite difficult to answer analytically, and wouldrequire an upper-level arsenal of mathematical tools, but intro stu-dents can tweak the code very easily to explore this scenario.

Thus, the use of VPython has the pedagogical virtue of empoweringstudents to engage in more physical modeling, and it enables themto better visualize processes, both of which in turn strengthen stu-dents’ conceptual understanding.3 Finally, a very straightforwardbenefit for introductory students is that they are exposed to a lan-guage, Python, that is fast becoming the premier tool for scientificcomputation.

The structure of the book is as follows. We start in Chapter 2with some preliminary exercises to get students familiar with theinterface and basic coding in VPython. In Chapter 3, we thenturn our attention to one-dimensional motion and motion diagrams.Quite a lot of emphasis is placed in Workshop Physics, as well asRealTime Physics,4 on describing basic motion in multiple represen-tations: verbally, in graphical form, and with mathematical equa-tions. Physics education research has shown that real conceptualand problem-solving progress occurs when a student can move flu-idly between these various representations of motion.5 The idea inthis chapter is to bolster students’ comprehension of position- andvelocity-graphs, which are one layer removed in abstraction fromthe literal description of the motion, by having them program anobject performing a simple kind of motion on the screen and then3R. Chabay, B. Sherwood, “Computational Physics in the introductory calculus-based

course”, Am. J. Phys. 76, 307 (2008).4D. Sokoloff, R. Thornton, P. Laws, RealTime Physics - Active Learning Laboratories (JohnWiley & Sons, 2012).

5A. Van Heuvelen, “Learning to think like a Physicist: A review of research-based instruc-tional strategies,” Am. J. Phys. 59, 891 (1991).L.C. McDermott, “A View from Physics” in Toward a Scientific Practice of Science Education(Lawrence Erlbaum Assoc., 1990).

2

Page 12: VPython for Introductory Mechanics: Complete Version

3

having VPython generate the corresponding motion graphs. In asense, it is the computational analogue to the common laboratoryexercise of using a motion sensor and walking in front of it.

In Chapter 4 we assume the course has by now advanced to a discus-sion of average and instantaneous velocity and acceleration. (In atraditional intro course, this may come very quickly.) We use someof these ideas to introduce the basic Euler method at the heart of allnumerical simulation encountered here.

In Chapter 5, we return briefly to the realm of plotting formulas, asthe course is now at the point of exploring projectile motion, i.e.,two-dimensional motion under constant acceleration. This topic isnaturally suitable for adding a computational facet. Exact analyticalresults (such as the range formula) can be easily tested numerically,for instance, as outlined in the exercise section of this chapter. Then,additional complications can be added (such as a sloped ground). Weend by having students code a “hit-the-target” game.

Chapter 6 in many ways strikes at the heart of mechanics. We arefinally ready to simulate Newton’s laws, and the full power of com-putational physics is revealed for the first time. We can see the kindsof motion that Newton’s laws actually give rise to, given the forcesacting on a particle and the particle’s initial state. We specificallyhighlight three important problems in order of increasing difficulty:the 1D mass-spring problem, projectiles traveling through air, andthe orbits of planets and comets. What makes this approach so po-tent in the context of an introductory course is that the analyticalsolutions are toomathematically challenging to derive and thereforeremain beyond reach for this audience. Yet, the numerical pathwayis accessible.

For Chapter 7, it is assumed that the course has now reached a dis-cussion of momentum and energy. We chose the binary star system

3

Page 13: VPython for Introductory Mechanics: Complete Version

4 Chapter 1 Introduction

as a vehicle for introducing the concept of center-of-mass and to tieit to momentum conservation. We then return to the mass-springproblem to illustrate the conservation of mechanical energy in thissystem. The Rutherford experiment can be skipped, but it providesa nice preview to electrostatics.

Maybe unsurprisingly, we now follow up with rotational motionand angular momentum, which often represents the last materialcovered in the semester. We end with what we believe to be twoengaging final examples - the gravitational “slingshot” and chaoticorbits - as a kind of capstone project for students to explore.

Lastly, before we get started, all the VPython codes featured in thisbook can be accessed online athttps://scholar.dickinson.edu/vpythonphysics/ .

4

Page 14: VPython for Introductory Mechanics: Complete Version

Getting Started with VPython

2.1 “Hello.”

VPython is a language that is pretty easy to use, once you get used toit. Python is becoming widely used by scientists around the world,and VPython is a visual implementation of it. It will help you visu-alize the physics you will be learning.1

To learn the basics of programming in VPython, the first thing wewill do is one of the simplest – having the program print the phrase“Hello, world!” – a traditional first program.

To do so, we will be in the Glowscript-VPython programming envi-ronment – an environment that is easy to use and understand. Hereis what you do:

1. Launch a web browser (try Google Chrome), and go to the sitewww.glowscript.org . The webpage will look like this:

2. Sign in with a Google account.

3. Follow the link where it says “your programs are here.”

4. Click on the “Create New Program” link.

5. In the dialog box that appears, type the title “MakingShapes”,then click the “Create” button.

1See also D. Schroeder, “Physics Simulations in Python” (2018).

Page 15: VPython for Introductory Mechanics: Complete Version

6 Chapter 2 Getting Started with VPython

Figure 2.1: The Glowscript webpage.

6

Page 16: VPython for Introductory Mechanics: Complete Version

2.1 “Hello.” 7

6. You will now see an editing space that is blank except for theline “GlowScript 2.8 VPython” (possibly with a different ver-sion number). Click in the white space below that line andtype the following, verbatim:

print("Hello, world!")

7. Then click the “Run this program” link at the top of the page.Your editing space should then vanish, replaced by a new textarea with the words “Hello, world!”

8. Click on ”Edit this program” and replace “Hello, world!” withsomething else. Run the program. You should get similar re-sults.

If the program didn’t work, check the spelling and capitalization andpunctuation. Make sure that you typed the line precisely as shownabove.

GlowScript-VPython is a programming environment that storesyour programs in the cloud. The interface is very spare – however,there should be no difficulty just starting it up, making new pro-grams, saving them, and managing them.

If you click “Edit this program”, you can see the program you justtyped. The first line, which is the same for all GlowScript programs,tells the system the language (VPython) and version (2.8) that is tobe used. You must have this line, and you should always just leaveit alone.

The next line tells the computer to call the print function and passesto it a string of characters. Don’t worry that you don’t know whatthe italicized words mean – we’ll explain them here:

7

Page 17: VPython for Introductory Mechanics: Complete Version

8 Chapter 2 Getting Started with VPython

• The function is a pre-defined task that does something – in thiscase, print to the screen. Just as you don’t need to know howa square-root key on a calculator works, a function does itsjob on the information passed to it. This information is calledthe argument or the parameter (they are slightly different, butthere is not much of a difference). Here the argument is thestring.

• The string is text that is either single- or double-quoted.• To tell the program what to do it and when, the function iscalled, which is done in the act of stating the function (here,“print”).

2.2 Box – Your First Shape

Now, let’s do something a bit more exciting.

On a new line below your print command, type the following com-mand:

box()

Here you’re calling a function called box, and passing it no argu-ments at all (but notice that you still need the parentheses). Run theprogram again, and you should see a black rectangular area (called acanvas) containing a light gray square (the box), such as one shownin Figure 2.2. Again, this function is doing a lot of work “under thehood”, but you do not need to concern yourself about how.

The box that you see on the screen is actually three-dimensional onthe screen. You are viewing it closely from one side, so it appears as

8

Page 18: VPython for Introductory Mechanics: Complete Version

2.2 Box – Your First Shape 9

Figure 2.2: A Simple Box

a square. To change the perspective, you can do three things:

• Rotate: Right-click button on your mouse and drag the boxone way or another, or, if you don’t have a right mouse button(such as on a Macintosh), press the control key and drag usingyour mouse or trackpad.

• Zoom: Use the scroll wheel on your mouse, or, if there isn’tone, press the alt or option key and drag using your mouse ortrackpad.

• Pan: Hold down the shift key while you drag using the mouseor trackpad.

You can change the attributes of your box by passing some differ-ent parameters to the box function. Try typing this to replace theoriginal box line:

9

Page 19: VPython for Introductory Mechanics: Complete Version

10 Chapter 2 Getting Started with VPython

box(pos=vector(1,0,0),size=vector(.5,.3,.2),color=color.green)

Here you’re providing three parameters, separated by commas, andyou’re identifying them by their names, which means you can pro-vide them in any order. The pos parameter specifies the positionof the center of the box in Cartesian coordinates; the size parame-ter specifies its dimensions (so here, it is not a cube; and the colorparameter is self-explanatory. In the first two cases, the parametervalues are three-dimensional vectors, which you create using thevector function. We will be learning more about this powerful func-tion soon. This function in turn takes three parameters, x, y, and z,which are usually given in that order. When first presented and be-fore any rotation, the x direction points to the right; the y directionpoints up; and the z direction points directly outward, toward you(or “out of the screen”).

You can learn more about other colors by clicking the Help linkat the upper-right corner of the window. It might be beneficial toopen the help page in a new browser tab. Then, from the seconddrop-down menu in the left sidebar, choose “Color/Opacity”.

There you will find a list of pre-defined colors, and also see how youcan use the vector function to create arbitrary colors.

Exercise: Create at least two more boxes, so you’ll have a total of atleast three, each with different positions, shapes, and colors. Keeptheir positions within the range -5 to 5 in each dimension, and keeptheir sizes small enough to leave plenty of room for more shapeswith that range. Make sure to “Grab” (a MacOS program) a screen-shot of what you did.

10

Page 20: VPython for Introductory Mechanics: Complete Version

2.3 Another shape 11

2.3 Another shape

Fortunately, VPython provides functions for creatingmany differentshapes, but in this course you’ll need just two others: spheres andcylinders. Try this instruction to create a sphere:

sphere(radius=0.25)

Thesphere function can also accept thepos andcolor parame-ters, so use those now to change the defaults according to your taste.Don’t forget to separate the parameters by commas!

2.4 Comments

Sometimes you want to have some comments to remind you what acertain line or area of a program is doing. All you need to do is put a# sign in front of the comment. Then VPython simply ignores every-thing following the # sign on that line. (It is very easy to “commentout” a line of code you want to not run, sometimes as a diagnostic.Then you can remove the # sign if you want the program to executethat command).

Exercise: Put a multi-line comment at the top o your program rightafter the line “GlowScript 2.8 VPython”, to indicate the name of yourprogram, your own name, and the day when you created it, andto give a one-sentence description of what it does. (From now on,please include a similar comment at the top of every program thatyou write.)

11

Page 21: VPython for Introductory Mechanics: Complete Version
Page 22: VPython for Introductory Mechanics: Complete Version

Moving Objects UsingFormulas

In this activity, you will be doing four simple exercises. In threeof them, a ball will move with either constant velocity or in in thepresence of a constant force. In the last, you will move a planet (justa large ball!) around the Sun.

3.1 Motion of a Ball with Constant Velocity

Examine the program provided for you in Figure 3.1. Type it in.Please note that the indentations are important (as is capitalization,usually).

Figure 3.1: Motion of a ball with constant velocity

What is each line doing? You can probably figure it out using thecommented-out lines. Now run the program. What is happening?

You probably found that this program is having a sphere move hor-izontally at a constant velocity. The command in line 14:

Page 23: VPython for Introductory Mechanics: Complete Version

14 Chapter 3 Moving Objects Using Formulas

x = x0 +v*t

is telling the program to take the original value of x, x0, and to adda constant velocity times the time elapsed t. This works, but wewill see in the next chapter that it is not the most elegant way ofupdating the value of x.

3.2 Motion of a ball with constant velocitywith a plot of position vs. time

Looking at the motion of the ball is fine, but plotting the values ofposition, velocity, or acceleration versus time is a way to visualizewhat is happening.

Take the first program, copy it with a new name, and add commandsto plot the ball’s position with respect to time. To do this, you mustset up a graph and declare its width and height:

Your program should look something like the one in Figure 3.2:

14

Page 24: VPython for Introductory Mechanics: Complete Version

3.2 Motion of a ball with constant velocity with a plot ofposition vs. time

15

Figure 3.2: Program Illustrating Graphing Commands

The command graph in line 3 sets up a graph with width 400 pixels,height 200 pixels, with an x-axis labeled “time” and a y-axis labeled“position”. The set-up graph is called “g1” for ease of use. Line 4uses the command gdots to say how the data is to be plotted, andcall it “xDots”. Here, it says that green dots should be used in thegraph called “g1” that was set up in the line before. Finally, line 21says that “xDots” should be plotted with the values of “t” (for time)for the x-coordinates, and the values of “x” (for position) for the y-coordinates.

Your plot should like what is shown in Figure 3.3. Is this what youwould expect? Why?

15

Page 25: VPython for Introductory Mechanics: Complete Version

16 Chapter 3 Moving Objects Using Formulas

Figure 3.3: Plot of position versus time for ball with constantvelocity.

3.3 Motion of a Ball Being Dropped fromRest Near the Surface of the Earth

Now, let’s simulate the motion of a ball being dropped from a heightof two meters.

Questions: What has to be done to modify the second program tomimic the ball being dropped? What is different about this ball’svelocity compared to the ball’s velocity in the second program?

What does the position-time plot look like now? How is it differentfrom the previous plot? Why?

Plot the velocity versus time. How does this compare to the currentposition versus time plot and the previous position versus time plot?

16

Page 26: VPython for Introductory Mechanics: Complete Version

3.4 Stop and Go 17

3.4 Stop and Go

In the previous section you probably discovered that instead of usinga constant speed v0, you needed to increment the speed with everypass within the WHILE loop.

Now let’s use a similar idea to make the ball move to the right at aconstant speed for 2 seconds, then to have it stop and sit there for 2second, and then to have it move to the left at a constant speed for2 seconds.

Discuss a possible strategy with your partners. You may find thatthere are multiple ways in which you could accomplish this objec-tive. One way would be to have three different WHILE loops - oneafter the other. However, perhaps a more elegant approach uses theif-then-else syntax - a core syntax structure of any programminglanguage. In VPython, it gets implemented in a very intuitive way:

If (“Condition to be tested”):“Execute these commands”

Else:“Execute those commands”

Here “Condition to be tested” should be something like t<2, t>2,ort==2, for example. Notice the double equal signs that are neededbecause the line should be interpreted as a test of a conditional state-ment (and not an assignment). Note that the indentations are es-sential - horizontal alignments signify and enforce structure in anyPython program.

Can you incorporate if-statements tomake the ball move to the right,stop, and then move to the left without any discontinuities? It may

17

Page 27: VPython for Introductory Mechanics: Complete Version

18 Chapter 3 Moving Objects Using Formulas

take you a while to get the third part right.

3.5 Motion of a Planet

In Figure 3.5 examine the program simulating the motion of a planet(the Earth) around the Sun. This is a very simplified depiction; itdoes not take into account gravity or any of the laws of planetarymotion. It merely assumes the Earth’s orbit is a perfect circle (whichin reality is not too far from the truth). In the program, note thatthere are cosine and sine terms, to define the x and y positions.

Figure 3.4: Simplified Motion of a Planet Around the Sun

The term omega, written as ω, is called the angular velocity (or thefrequency). You will see this term later in the course when we dis-cuss rotational motion. Its value in the program will help you to see

18

Page 28: VPython for Introductory Mechanics: Complete Version

3.5 Motion of a Planet 19

how it is defined.

Exercise: Change the parameters of the provided program. Howdoes the executed program change?

Exercise (optional): Define a third sphere and call it “Moon”. Usethe same approach to make the Moon revolve around the Earth,while the Earth still simultaneously revolves around the Sun. Hint:Vector addition will be very useful here. You have to add somethingto the position vector of the Earth.

19

Page 29: VPython for Introductory Mechanics: Complete Version
Page 30: VPython for Introductory Mechanics: Complete Version

A First Look at SimulatingMotion

In the last activity, we managed to move objects on the screen byrepeatedly evaluating the position function, x(t), for successivelylarger time values. This iterative evaluation of the functionwas donein the WHILE loop.

We were also able to graph the values in a position-time graph.

This approach was quite powerful already, but it also limits whatwe can do. For example, it would already be quite difficult to makean object move forward, stop for a while and then move backwardusing this approach, as you probably discovered in the last chapter.Furthermore, this approach also imposes solutions rather than nu-merically finding them, thus sort of bypassing the underlying phys-ical laws, as we will see later.

For these reasons, we would like to move from a mere evaluation ofa function to an actual simulation of a physical process in real time.Today, we will take our first step in the direction of a true numericalsimulation of physics.

4.1 The Physics

Let’s start with a piece of physics that you already know – the for-mula for average velocity in one dimension – and then translate itto a statement a computer can understand. So, average velocity isdefined as,

Page 31: VPython for Introductory Mechanics: Complete Version

22 Chapter 4 A First Look at Simulating Motion

vavg = ∆x

∆t= x2 − x1

∆t(4.1)

In words, the average velocity over a time interval of motion is de-fined as the displacement divided by the elapsed time.

As a general rule, computers cannot handle continuous motion.Therefore, in order to make any simulation of real physical motionlook realistic, we will have to “chop up” the true continuous motioninto many, many frames separated by very small time intervals. Thesituation is not unlike watching a movie where we perceive continu-ousmotionwhen in reality we are being exposed to a rapid sequenceof still images.

The upshot is that we will want to make our time interval ∆t reallysmall in Equation (4.1). Over the course of this small time intervalwe would not expect the velocity to change very much, so a prettygood assumption is that it is simply constant over this interval. Thisalso means that the average velocity is just the same as this con-stant velocity and we can drop the subscript “avg”. If we then solveEquation (4.1) for x2, we get:

x2 = x1 + v∆t (4.2)

Here we assumed that ∆t was sufficiently small, which allowed usto omit the subscript avg.

Let’s describe Equation (4.2) in words: Between two frames sepa-rated in time by ∆t, we can compute the position of the object inthe new frame, x2, based on the position in the current frame, x1,and the velocity of the object, v. We simply have to add v∆t to x1.

Now all we have to do is repeat the step in Equation (4.2) over andover again. Every time we advance forward in time by the small

22

Page 32: VPython for Introductory Mechanics: Complete Version

4.2 The Basic Code 23

amount ∆t. And every time, we replace the starting position x1 bythe ending position x2 of the previous step. In other words, we wantto use Equation (4.1) recursively in order to evolve the position ofour object forward in time, step by step.

So far, we have assumed that v in Equation (4.2) would remain con-stant in each successive step, but this does not have to be the case.In general, we can allow the velocity v to get updated as well witheach new iteration. We will see some straightforward examples inthe section 4.3. The procedure we have described here is also knownin the numerical analysis community as the Euler Method.1

4.2 The Basic Code

Now that we a taste of the physics involved, how do we translatethat idea into code a computer can interpret? Let’s take a look atthe following few lines of VPython code - see Figure 4.2.

We see that the core of the program is contained in the WHILE loop,as before. Let’s start our discussion with the central line, namelyLINE 22:

x = x + v ∗ dt (4.3)

As a mathematical statement this is, of course, nonsense. But weshould not interpret the equal symbol in the mathematical sense. Itis not an equality. It is an ASSIGNMENT. “x” is a variable that holdsa certain number, andwhenever you see “x = something” this signalsthat the value stored in the variable “x” is about to be updated.

So Equation (4.3) should be read in two parts. The expression to1Named after the mathematician and physicist Leonhard Euler.

23

Page 33: VPython for Introductory Mechanics: Complete Version

24 Chapter 4 A First Look at Simulating Motion

Figure 4.1: The basic code

the right of the equal sign is computed first based on the currentvalue of x. Secondly, the “x = ” part then assigns the result of thatcomputation to the variable x. The upshot is that x is updated andnow holds the new value.

Thus, if we had to translate the statement in Equation (4.3) into amathematical equation, we would say:

x2 = x1 + v∆t,

where x2 is the new value and x1 is the old value of position. Notealso that “dt” in Eq. 4.3 should not be interpreted as a differential inthe Calculus sense but represents a small time interval, defined inLINE 12 as 0.05.

We are now in a position to discuss the entire code. Line 4 and 5set up a position graph (time on the horizontal axis, position on the

24

Page 34: VPython for Introductory Mechanics: Complete Version

4.3 Exercises 25

vertical axis). LINE 8 defines the object we want to move around inspace – a red sphere of radius 0.1. Lines 11-13 set the initial condi-tions as well as the size of the small time interval, dt. Within theWHILE look, we keep updating the variable x and then, using this,to update the position of the object using the command in LINE 19:obj.pos=vector(x,0,0). Here objwas defined as the sphere, and posis an attribute of the sphere, namely the position (i.e. location) of thesphere’s center. This position is a three-dimensional vector whichwe create using the vector command. Finally, the xDots.plot(t,x)command in LINE 20 appends the newest data point to our positiongraph.

The last line, Line 23, updates the time variable. This is necessary inorder to test the conditional of the WHILE loop (t<3), as well as forthe purpose of plotting the position (and velocity) graph. It does not,however, come into play in calculating the position of the object – animportant difference from the previous approach of simply plottingthe function x(t).

4.3 Exercises

1. • Run this program to make sure it works. Describe whatyou see.

• Modify the code so that during the first second, the ball ismoving to the right as before, but for the second secondit stays still, and during the third second, it returns tothe original starting point. Also have VPython generatethe corresponding position-time graph.Hint: Think about how you could use if-then statementsto accomplish this task.

25

Page 35: VPython for Introductory Mechanics: Complete Version

26 Chapter 4 A First Look at Simulating Motion

2. • Discuss with your group how you would have to modifythe code printed above to make the object accelerate tothe right at constant acceleration. Hint: Think about therole of “v”!

• Once you verify that the code really does produce anaccelerating object on the screen, let’s have VPythongenerate the position-time graph, as well as the velocity-time graph. Ideally, the data would be displayed in twoseparate graphs. You may have to duplicate and slightlymodify some of the lines already appearing in the sam-ple code.Take a screenshot of the code, as well as the two graphsto include in your lab notebook.

• Now that you have the position-time graph, verify thatit agrees with the first kinematics equation: x(t) = x0 +v0t + 1

2at2. You can do this, for instance, by evaluatingthe formula at a particular time (for the initial velocityand the acceleration that appears in your code). Doesthis point lie on the the graph?

26

Page 36: VPython for Introductory Mechanics: Complete Version

Visualizing Projectile Motion

In this activity, you will extend what you learned in Chapter 3 aboutthe kinematics equations into two dimensions. These equations de-scribe the motion of a projectile undergoing a constant acceleration.

Usually a projectile, such as a thrown ball or a launched rocket, ispropelled at an angle to the ground θ, usually measured from thehorizontal. One must take into account the components in the hori-zontal (usually “x”) and vertical (usually “y”) directions.

5.1 The Physics

The kinematic equations are as follows:

x = x0 + vx0t + 12

axt2; (5.1)

vx = vx0 + axt; (5.2)

andv2

x = v2x0 + 2ax(x − x0). (5.3)

While “x” is used above in Equations (5.1), (5.2), (5.3), they are simplyplaceholders; one can easily replace them with “y”:

y = y0 + vy0t + 12

ayt2; (5.4)

vy = vy0 + ayt; (5.5)

andv2

t = v2y0 + 2ay(y − y0). (5.6)

Page 37: VPython for Introductory Mechanics: Complete Version

28 Chapter 5 Visualizing Projectile Motion

Therefore if we have a projectile launched at an angle θ to theground, then the horizontal component of the velocity is

vx = v cos θ (5.7)

and the vertical component of the velocity is

vy = v sin θ. (5.8)

So, if we throw a ball at angle θ = 43◦, with a velocity of 10 ms , then

the initial x- and y-components of the velocity are (cf. Equations(5.7) and (5.8))

vx0 = 10m

scos 43◦

andvy0 = 10m

ssin 43◦.

As for acceleration, if we are talking about locations near the surfaceof the Earth and ideal conditions (no atmosphere, so therefore nowind), there is no acceleration in the horizontal (x) direction. Theonly acceleration is the familiar ay = −g = −9.8m

s .

5.2 Exercises

5.2.1 Projectile over Flat Ground

Use Equations (5.1), (5.2), (5.4), (5.5), (5.7), and (5.8) to write VPythoncode that simulates the flight of a projectile. Make the projectile asphere of radius 0.1. Assume that there is no air resistance. Assumethat we launch the projectile at the origin (0,0), and stop the pro-jectile motion once it hits the ground at y = 0. This means that theterrain is flat. Draw a line (or horizontal plane) that indicates this.

28

Page 38: VPython for Introductory Mechanics: Complete Version

5.2 Exercises 29

Figure 5.1: A Projectile Trajectory Over a Flat Slope

To accomplish this last condition, use the following while loop:

while(y>-0.001)

Your program should have an output such as depicted in Figure 5.1.

One thing to keep in mind is the built-in unit for angles in VPythonis always radians. This means that you will need to convert anyangle in the argument of a trig-function from degrees to radians.

Now play around with launch angle at constant launch speed. Makea table of the range for each launch angle. For what angle θ dowe seem to get the largest range? Is this range consistent with thetheoretical formula for the range of a projectile, given by

29

Page 39: VPython for Introductory Mechanics: Complete Version

30 Chapter 5 Visualizing Projectile Motion

R = v20 sin 2θ

g. (5.9)

To answer this question, open up Excel, have it compute the theo-retical value from Equation (5.9) at regular angle intervals, and thencompare the values with your numerical results from VPython sim-ulations.

5.2.2 Projectile over Sloping Ground

Now let’s make the ground not level (or flat). Let’s have a steadydownward slope. Redraw the line (or plane) so that it tilts downwith a slope of rise/run = -0.1.

Thewaywe can simulate that in the code is bymodifying theWHILEstatement. How do you have to do that? Once your group finds asolution, implement it in the code.

What angle now produces the largest range?

Repeat the simulation, but with a terrain that gently slopes up, witha slope of +0.1. What is the best angle now?

5.2.3 Projectile Striking a Target

In addition to the projectile and the (flat) ground, draw in a station-ary sphere of radius 0.5. You decide the coordinates of this stationarysphere.

30

Page 40: VPython for Introductory Mechanics: Complete Version

5.2 Exercises 31

Make the code stop if or when the projectile hits the object, whichwe will define as anywhere within the volume of the object. If wedo not hit the sphere, then make the code stop as before when theground it hit. Because we are only thinking in two dimensions, inorder to hit the sphere we need to just have the projectile get within0.5 units of the center. How can we do that?

Hint: there is a kind of brute-force approach using the Pythagoreantheorem, but there is also a much more elegant method using thetwo position vectors associated with the projectile and the targetsphere. Can you see how you could use the difference of these twovectors?

One thing that will probably need here is the following command:

BREAK

If this command is encountered within a WHILE-loop, we im-mediately leave the loop and continue with statements outside of it.Oftentimes, you will find the break command wrapped inside anIF-statement all inside a while-loop.

Projectile motion is a fairly easy thing to simulate in VPython. Inthe next chapter, you will see how to make the simulation morerealistic by the incorporation of air resistance in the code, with theuse of vectors.

5.2.4 Mystery Code

Scan the following VPython code and annotate each line. Discusswhat you think this code will do. Make a prediction as to the kindof motion that would be highlighted.

31

Page 41: VPython for Introductory Mechanics: Complete Version

32 Chapter 5 Visualizing Projectile Motion

Note that in the VPython environment, to raise a quantity to somepower, you do NOT use the carrot-symbol, but instead you use twostar-symbols “∗∗”. Thus, x2 would be represented in the code asx ∗ ∗2.

32

Page 42: VPython for Introductory Mechanics: Complete Version

Simulating Central-ForceProblems

6.1 Stating the general problem and apossible line of attack

In Chapter 4, we learned how we could use an iterative procedure(called the Euler method) to advance the position of an object insmall increments based on its current velocity. This allowed us tonumerically obtain x(t) given v(t). In other words, we performeda numerical integration: given the known velocity-time graph, wegenerated the position-time graph.

The task in many physics problems is slightly different, however.Very often, we know the force acting on an object at all points inspace, and we would like to somehow calculate the object’s trajec-tory in response to the forces it encounters. How do we do that?

So, let’s assume that we know the force that is acting on an object asa function of the object’s location. What this means is that nomatterwhere the object happens to be, we can calculate the force that itexperiences there. Mathematically speaking, what we are given isthe force-function, F⃗ (r⃗). This notation communicates that we canevaluate a force vector, F⃗ , by inserting a position vector, r⃗, into afunction. Mathematicians would call such a function a map from R3

to R3. A good example are the so-called central-force problems, suchas the gravitational force a comet feels in the vicinity of the sun.

We also know that the force on the object is related to the accelera-tion of the object via Newton’s second law:

F⃗ = ma⃗ (6.1)

Page 43: VPython for Introductory Mechanics: Complete Version

34 Chapter 6 Simulating Central-Force Problems

This means that simply dividing the force-function by the object’smass gives us the acceleration function a⃗(r⃗).

Now that we have the acceleration, how do we get the trajectory?Recall that we faced a somewhat similar task in Chapter 4. There weknew the velocity and were able to compute the position. But nowwe are one step further removed. We know the acceleration, notvelocity. What’s more, we know the acceleration not as a functionof time, but as a function of position.

You may know that in these types of problems, in order to computethe object’s trajectory, we must know how the object was initialized.At what position was it released and what velocity did it have at thatmoment? These two things must be known to us if we are to findthe unique trajectory - they are called the initial conditions.

So here is the basic idea. Let start from this position and velocity inour code, call them: x⃗1 and v⃗1. From x⃗1 we can compute the forceat that location and thus the acceleration a⃗1. Using this a⃗1, we nowupdate the velocity. Here we make use of the formula for averageacceleration,

a⃗avg = ∆v⃗

∆t. (6.2)

As the time interval gets very small (and, in the limit, infinitesi-mal), the average acceleration becomes the instantaneous acceler-ation, and so,

v⃗2 = v⃗1 + a⃗ ∗ ∆t. (6.3)

This completes the second step.

In the third and final step, we now use this new velocity to updatethe position, using the vector-verson of Equation (4.2), namely:

x⃗2 = x⃗1 + v⃗2 ∗ ∆t. (6.4)

34

Page 44: VPython for Introductory Mechanics: Complete Version

6.1 Stating the general problem and a possible line of attack35

Now that we have computed the new position vector x⃗2, we canstart the whole procedure over again by first computing the newforce and acceleration (F⃗2, a⃗2), then the new velocity (v⃗3), and thenfinally the new position (x⃗3). Schematically, we are proceeding insteps given by the following flow chart:

In summary, we basically apply the Euler method twice, once forthe velocity and then for the position. Notice also that we updatethe velocity first and then use the new velocity to update positionsecond. It turns out that this order of operation is often superior tothe reverse order in terms of computational accuracy. It is called theEuler-Cromer method 1.

1A. Cromer, Stable solutions using the Euler Approximation, American Journal of Physics,49, 455 (1981).

35

Page 45: VPython for Introductory Mechanics: Complete Version

36 Chapter 6 Simulating Central-Force Problems

6.2 A first example: The mass-spring problem

To illustrate the method, let’s get our feet wet with a relatively sim-ple problem - a mass on a horizontal spring. All we have to remem-ber is Hooke’s law for ideal springs,

F (x) = −kx, (6.5)

where k is called the spring constant which corresponds to the stiff-ness of the spring, and x represents the amount of stretch (if posi-tive) or compression (if negative) of the spring. We should appreci-ate this formula as the one-dimensional version of F⃗ (r⃗) from before.Dividing Equation (6.5) by the mass of the object that we attach tothe end of the spring yields the object’s acceleration.

Let’s look at the basic VPython code, shown in Figure 6.1, to seehow the Euler-Cromer method gets implemented in practice here.The basic steps (outlined in the flowchart in the previous section) arecontained in lines 24 through 27. Line 28 is not absolutely necessary,but it is included for the purpose of making position and velocity-time graphs.

Notice also how easy it is in VPython to draw a spring-mass setup- we basically select a sphere for the end-mass and a helix for the

36

Page 46: VPython for Introductory Mechanics: Complete Version

6.3 Exercises 37

Figure 6.1: The basic code simulating a mass at the end of a spring

spring. The only thing we have to take care of is to deform the helixin dependence upon the position of the end-mass.

6.3 Exercises

• Run the program in Figure 6.1 and examine the position-timegraph. What does the graph look like? What math functiondoes it seem to follow? What about the velocity-time graph?

• What can you say about the relationship between theposition-time graph and the velocity-time graph. Is there

37

Page 47: VPython for Introductory Mechanics: Complete Version

38 Chapter 6 Simulating Central-Force Problems

a phase difference between them, and if so, approximatelywhat is it?

• Find the place in the code where the initial conditions (x0and v0) are specified. Try running the program with afew different sets of initial conditions. Does the period ofoscillation seem to depend on this choice?

• Find the place in the code where system’s physical parametersare specified, namely the spring constant and mass. Changeone of these parameters at a time, and observe qualitativelyhow it changes the period of oscillation.

• What if you double (or triple) both the mass and the springconstant? Do the graphs change?

• Are your observations above consistent with the well-knownformula for the period of oscillation, T , given below?

T = 2π

√m

k

6.4 A second example: Projectile motion withair drag

As a second example - one that is slightly more difficult while alsoshowing off some of VPython’s strengths - let us consider a pro-jectile launched through the atmosphere. Here we don’t want toneglect air drag, as is customary in introductory physics, and as wedid in Chapter 5. Instead, we recall that a good formula for the drag

38

Page 48: VPython for Introductory Mechanics: Complete Version

6.4 A second example: Projectile motion with air drag 39

force (under certain assumptions) is given by,

F⃗D = 12

ρACDv2(−v̂), (6.6)

where ρ is the density the medium (here, air), A the cross-sectionalarea of the projectile, and CD the coefficient of drag. We see thatthe magnitude of the drag force is proportional to the square of thespeed, and that its direction is opposite to the motion. This latterpoint is mathematically represented by the last term in Equation(6.6), where v̂ is the unit vector in the direction of instantaneousmotion, or v̂ = v⃗/|v|.

You might be thinking that the changing direction of the drag forcewould be difficult to “handle”, and ordinarily you would be right.In fact, this facet of the problem coupled with the quadratic depen-dence on speed makes this problem impossible to solve in closedform with pencil and paper. So here we now encounter our first in-stance of a problem that has no closed-form analytical solution andwhere we rely on a computer to give us the solution numerically.

We said “ordinarily” because within the VPython environment thereexist high-level commands that will make this problem substantiallyeasier. Particularly nice are the built-in vector operations that in-clude easy evaluations of dot and cross-products between vectors, aswell as evaluations of a vector’s magnitude and direction. For ourpurposes here, we want to highlight two operations we can performon a vector A:

• mag(A) andmag2(A), where the output yields the length andlength-squared of that vector, respectively.

• A.hat, which produces from the vector A its unit vector (bydividing it by its length). This syntax treats the directionality(given by the unit vector) as a property of the vector. It is justlike any other property of a vector, such as A.x, which yieldsthe x-component of the vector A.

39

Page 49: VPython for Introductory Mechanics: Complete Version

40 Chapter 6 Simulating Central-Force Problems

Armed with these commands, implementing Equation (6.6) shouldseem a lot more straightforward. Let’s look at the basic code first(see Figure 6.2).

Figure 6.2: The basic code simulating a the trajectory of a projectilewith air drag

One thing to point out before we delve in is that everything here isin SI-uits. This means that whenever you encounter a number (as-signed to a variable), that number should be considered to have theappropriate SI-unit. So, for example, Line 10 states: speed=10. Thismeans that we set the speed of the projectile to 10 m/s. Similarly,Line 12 defines the density, rho = 1.2, as 1.2 kg/m3 (the density ofair). Since the SI-unit system is closed, any calculations that thecode performs will automatically be in the appropriate SI-unit forthat variable.

We can start by looking at Lines 13 through 15. Here we first com-pute the x- and y- components of the velocity vector from the speed

40

Page 50: VPython for Introductory Mechanics: Complete Version

6.4 A second example: Projectile motion with air drag 41

and launch angle. Line 15 is interesting: ball.v = vector(vx,vy,0).How should we interpret this statement? First, it is an assignment.The velocity vector on the right of the equal sign is assigned to aquantity called ball.v. The notation on the left side of the equal signsuggests that v is a property of ball. In fact, with this statement wedefine the velocity to be a property of the object we introduced ear-lier in the code and called ball. So now in addition to the propertiespos, size, and color by virtue of the ball being defined as a sphere,we have added the property v.

What is interesting is that ball.v has itself all the properties that avector can have, and so, for instance ball.v.x would refer to the x-component of the ball’s velocity vector. Similarly, ball.v.hat wouldgive the unit vector in the direction of motion.

Finally, let’s examine Line 23:

F=vector(0,-m*g,0) - 0.5*C*rho*Area*mag2(ball.v)*ball.v.hat.

You should recognize this as the net force acting on the projectile.The first part is the gravitational force near the surface of the earthand the second is the drag force. Notice that VPython automaticallyadds these two parts as vectors.

When you run the program you should get something like the fol-lowing:

41

Page 51: VPython for Introductory Mechanics: Complete Version

42 Chapter 6 Simulating Central-Force Problems

Notice that the code returns the approximate range of the projectilein the print statement. Also observe the shape of the trajectory. Itclearly deviates from the parabola - the highest point in the trajec-tory is not reached at the horizontal half-way point, and the descentis steeper then the ascent.

6.5 Exercises

• Run the program with different launch angles and determinethe angle that gives you the largest range. Without air-drag,it is fairly easy to prove that that angle is 45 degrees. What isit now?

• Let’s play a game. The object is to make the range as close to100 meters as possible. You are only allowed to change theinitial launch angle and speed. What combination gets youclosest to 100 meters? There may be more than one solution.

42

Page 52: VPython for Introductory Mechanics: Complete Version

6.6 Third Example: Trajectories of Planets and Comets 43

• Instead of modifying the initial conditions, as in the previousexercise, now examine the role of the projectile properties.The shape of the projectile enters the problem via the dragcoefficient CD; it can vary from as low as 0.05 (for a veryaerodynamic shape) to about 1.0 (for a cube). Adjust first themass and then the drag coefficient, and describe how thesetwo parameters affect the trajectory.

• Add to the code given above so that you can get two trajecto-ries on screen simultaneously. These two trajectories shouldcorrespond to two different projectiles (differentiated eitherby mass or drag coefficient).

6.6 Third Example: Trajectories of Planetsand Comets

Our final example is also the most famous in the sense of historicalsignificance - the Keplerian orbits of planets and comets around thesun. The perfectly circular orbit is one special solution to Newton’ssecond law. This is usually demonstrated in introductory physicsby setting the formula for the centripetal force equal to the gravita-tional force,

mv2

r= GMm

r2 , (6.7)

We set them equal because gravitation actually provides us with thecentripetal force necessary for moving in a circle. Solving Equation(6.7) for v yields the orbital speed as a function of the orbital radius,

v =

√GM

r(6.8)

43

Page 53: VPython for Introductory Mechanics: Complete Version

44 Chapter 6 Simulating Central-Force Problems

Proving that elliptical orbits also satisfy the governing equations ismuch more difficult and usually reserved for an junior-level coursein classical dynamics. The same goes for parabolic and hyperbolicorbits - the remaining cone sections. However, we can explore thoseorbits numerically using VPythonwithout any advanced knowledgeof physics.

Imagine for a moment that we had the power to launch a comet at aparticular distance from the sun, call it r0, as well as with a certaininitial velocity. It is not hard to see that if we chose a velocity ofzero, the comet would head straight for the sun; it would acceleratein a straight line toward the sun and be swallowed up by it. In fact,many people unfamiliar with physics think that this scenario is theonly one possible and that circular orbits are only feasible due toother planets or stars in the picture, or by some other magic (whichis, of course, ludicrous).

But what if we chose an initial velocity at right angles to the lineconnecting the comet to the sun? We would at least have a chanceof obtaining a circular orbit, but only if the speed in this directionmatched Equation (6.8). Indeed, this set of initial conditions wouldproduce a circular orbit.

Now imagine what would happen if the speed that we impart tothe comet at right angles did not match that speed. What if it weremuch smaller or larger than what Equation (6.8) demands? It standsto reason that we would then not recover a circular orbit, but whatdo we get instead? Let’s find out by running a numerical simulation!

The basic code is surprisingly short. In this version we decided forsimplicity to set the universal gravitational constant to 1, but youcan change it to the actual value in SI-units. In that case, however,you should also make themasses and distances involved realisticallylarge. The basic code, then, is shown in Figure 6.6. Feel free to make

44

Page 54: VPython for Introductory Mechanics: Complete Version

6.7 Exercises 45

the parameters more realistic; the mass ratio that appears here isonly 1:100, for instance. Nonetheless, we can use this simplifiedcode to explore the possible orbits.

Figure 6.3: The basic code simulating gravitational orbits.

6.7 Exercises

• Examine the code provided, make sure that you understandwhat each line does, and annotate.

• Use Equation (6.8) with the parameters given in the code tofind the orbital speed for a circular orbit. Enter this speed asthe starting speed in the code at the appropriate place. Doyou get a circular orbit?

• If you doubled the initial distance of the comet from the sun,what speed would be necessary now for a circular orbit? Tryit in the code.

45

Page 55: VPython for Introductory Mechanics: Complete Version

46 Chapter 6 Simulating Central-Force Problems

• Now select a starting speed that is smaller than the oneyou chose above. Observe the kind of orbit you obtain now.Does the orbit trace out the same path after each revolution?Astronomers call this scenario a closed orbit.

• What can you say about the orbital speed? Is it constant ordoes the comet appear to speed up at certain points? Explain!

• If you make the initial speed too small, you will see thatthe simulation eventually breaks down and returns non-sensical results. Why is that and what can you adjust toremedy the situation? [Hint: When the comet gets veryclose to the sun, the acceleration it experiences becomes verylarge. What line in the code is going to be adversely affected?]

• Let’s be even more creative. Instead of the normal law of uni-versal gravitation that decreases with the square of distance,what would happen in a universe ruled by a gravitationalforce proportional to 1/r? Make this change in the code, andstart with a circular (or near circular) orbit by using Equation(6.7) but with the new gravity to solve for orbital speed.

• Now lower the speed and observe the orbits that result. Whatis the most obvious qualitative difference about the orbits thatwe get now in this alternative universe?

46

Page 56: VPython for Introductory Mechanics: Complete Version

Conservation of Momentumand Energy

7.1 A binary-star system

In the previous chapter we considered the motion of a planet subjectto a central force that was always directed from the planet towardsthe origin where a star was sitting motionless. This is, of course,not quite correct, since the star also experiences a gravitational pulltowards the planet and must therefore also move. This motion isusually very small since stars tend to be much heavier than planets,but it is not zero.

Let’s consider now the full two-body problem. To give us maxi-mal flexibility in parameters, we can consider the two bodies bothstars in a binary-star system. We will creatively call the heavierstar “bigstar” and the lighter star “smallstar”. We could, of course,proceed exactly like before, modifying the code in Chapter 6 to in-clude the dynamics of the second object (i.e., the sun). But to illus-trate another important physical concept, namely that of momen-tum and momentum conservation, let us incorporate this quantityin the code.

To review briefly, momentum is defined by p⃗ = mv⃗. An objecthas momentum by virtue of having mass and velocity. We can alsotalk of the total momentum of a system of objects. In that case wesimply add the individual momenta of all the objects that make upthe system together (as vectors). Now, we can prove that when thissystem is isolated, in other words when nothing outside this systemexists that would push or pull on the objects within the system, thenthe total momentum of the system doesn’t change. We say that thetotal momentum is conserved.

Page 57: VPython for Introductory Mechanics: Complete Version

48 Chapter 7 Conservation of Momentum and Energy

Another useful concept in this context is the center of mass of a sys-tem comprised of discrete objects/particles. We can compute thecoordinates of the center of mass using the well-known formula,

xcom = m1x1 + m2x2 + ...

m1 + m2 + ...,

and similarly for the y-coordinate. Since VPython deals well withvector quantities, we can also dispense with the individual compo-nents and refer only the position vectors, r⃗i, of the objects them-selves:

r⃗com =∑

mir⃗i∑mi

. (7.1)

You may have learned that whenever the total momentum of a sys-tem is conserved, i.e., when there is no net external force acting onthe system, then the center of mass cannot experience any accelera-tion. In our notion, we can write,

a⃗com = d2

dt2 (r⃗com) = 0. (7.2)

The proof of this statement is actually not difficult and well withinthe reach of an introductory physics student. See if you can work itout yourself.

One of our objectives will now be to “prove” this property aboutthe center of mass numerically by simply computing its location foreach time-step and then to observe its motion across the screen. An-other will be to show that in this binary-star system, total momen-tum will be conserved. It should be conserved because the way wehave set up the problem, the system is clearly isolated - there are noother objects around at all.

48

Page 58: VPython for Introductory Mechanics: Complete Version

7.1 A binary-star system 49

Figure 7.1: The code for the binary-star system.

Let us again start with a code template - see Figure 7.1. One thingyou will notice immediately is that we are now not working in ar-tificial units (as before) and instead use the true value for the gravi-tational constant. That also forces us to use astronomically realisticvalues for all other quantities in the problem, such as for the massesand distances involved. Again, as long as all the inputs are in SI-units, so will all the computed outputs.

As you can see, in the first six command lines, we basically set upthe properties about the two stars. For instance, the bigger star hasa mass of 3 × 1030 kg - three times that of the smaller star. For

49

Page 59: VPython for Introductory Mechanics: Complete Version

50 Chapter 7 Conservation of Momentum and Energy

comparison, our sun’s mass is about 2 × 1030 kg. One of the thingsyou will have a chance to play around with is the mass ratio of thetwo stars.

The next line (Line 17) defines the computational time step. Thismight strike you as an incredibly large time step, especially com-pared to the values we have used before, but remember - everythinghas to be astronomical, including time. The time step of 105 sec-onds translates to a duration of slightly longer than an earth day.Compared to the period of revolution this is still quite small.

Lines 19 and 20 are recognized from Equation (7.1) as nothing otherthan r⃗com. The next two lines are there just so we can visualize thelocation of center of mass on the screen, here in the aspect of a greencone whose trajectory we will also keep track of via the “make_trail”command.

The iterative part of the program starts with Line 25. We define thevector, r, that runs from the small star to the big star. We could havealso reversed it, but it is important to be consistent. The way it isdefined, it will be parallel to the force on the small star and anti-parallel to the force on the big star. By Newton’s third law, thesetwo interaction forces must be equal and opposite.

Lines 30 and 31 implement Newton’s second law,

F⃗ = dp⃗

dt. (7.3)

If we solve this for the small change in momentum, we get: dp =Fdt; in other words, it takes a force to change the momentum. Thisis also sometimes referred to as the impulse-momentum theorem.Once we have calculated the new momentum, we can also updatethe position of the corresponding star, since momentum, of course,is intimately related to velocity - we get velocity by dividing the mo-mentum by mass. This way, we do not have to explicitly refer to

50

Page 60: VPython for Introductory Mechanics: Complete Version

7.2 Exercises 51

velocity at all in the WHILE loop.

7.2 Exercises

• Run the program - does the computed total momentumchange over time? Is physics correct? Also examine the code- is the result at all surprising?

• You will also notice that the center of mass does not staystationary, but that it moves on the screen. We can make thatmotion cease if we give the two stars initial momenta thatadd to zero. Show that right now (i.e., in Figure 7.1) they twoinitial momenta do not add to zero.

• Now change the initial conditions such that the total mo-mentum is in fact zero initially. What do you notice aboutthe center of mass motion on the screen? Also changethe viewer’s perspective to see the two-body motion fromdifferent angles.

• Make an additional change in initial conditions (positionsand velocities) and watch the orbits of the two stars aroundeach other. Consider turning on the “trails” on the orbits forbetter visualization.

• VPython allows you to view the motion from the perspectiveof different observers (or reference frames). The command isscene.camera.follow(bigstar). In the parenthesis appearsthe name of the object that you want to make as the referenceframe. In the command above we take the big star as theobserver’s reference frame. To make things less confusing,

51

Page 61: VPython for Introductory Mechanics: Complete Version

52 Chapter 7 Conservation of Momentum and Energy

turn off all the trails again.

• Now that you have explored the role of initial conditions abit, let’s turn to the mass ratio. Try one case where the ratiois much larger than 3, and then one case for the ratio is closeto 1. What do you conclude from those two scenarios.

7.3 Energy in the Spring-Mass System

In Section 6.2, we explored the motion of a mass at the end of aspring. We saw the sinusoidal motion that resulted from the com-bination of Newton’s second law and Hooke’s law. Now we canrevisit this problem and analyze it through the lens of potential andkinetic energy.

Remember that the potential energy stored in a stretched or com-pressed spring, also called elastic potential energy, is given by U =12kx2. Furthermore, the kinetic energy of the end-mass is given byK = 1

2mv2. Finally, the total mechanical energy is simply the sumof the two energies, Emech = U + K .

Modify the code, as given in Figure 6.1, in the following manner.

• Add some lines that will compute the three energies, U , K ,and Emech.

• Then, instead of plotting position and velocity as a functionof time, instead plot the three energies that are now beingcomputed at each time step. What do you observe? Is thetotal mechanical energy conserved over time? Explain!

52

Page 62: VPython for Introductory Mechanics: Complete Version

7.4 Simulating the Rutherford experiment 53

7.4 Simulating the Rutherford experiment

Another example that we will see is actually mathematically verysimilar to the binary-star system is the famous Rutherford scatteringexperiment. We know that two like charges repel via the Coulombforce. This force has the same structure as the law of universal grav-itation. It is given by,

F⃗c = kq1q2r2 r̂, (7.4)

where the Coulomb constant k = 9.0 × 109 N m2/C2 plays the roleof the gravitational constant, G. Notice how this force also dependsinversely on the square of the distance between the two objects, andthat it is again a central force (indicated by the direction vector r̂).

Ernest Rutherford’s experiment was to shoot alpha particles, whichare fast Helium nuclei, at a thin gold foil. The idea was to see ifand how the alpha particles would be deflected upon hitting the foil.What Rutherford discovered was that every once in a while the de-flection angle was very large so that the alpha particle was scatteredback to the source. The explanation for these large deflections is thatthe positive charge in the gold atoms is actually highly concentratedin the nucleus (and not smeared out). In fact, while the size of thegold atom is on the order of 10−10 meters, the nucleus is 100,000times smaller, i.e., on the order of 10−15 meters.

So if the positively charged alpha particle hits a gold nucleus closeto head-on, since the two repel it should be deflected back. At thesame time, the Gold nucleus should also experiences some recoil. (Ifit didn’t, momentum could not be conserved during the collision.)Let us now use VPython to explore the different scenarios that can

53

Page 63: VPython for Introductory Mechanics: Complete Version

54 Chapter 7 Conservation of Momentum and Energy

occur when we shoot an alpha particle at a gold nucleus.

While Equation (7.4) is very similar in form to Equation (6.7), thelength scales of the nuclear-collision problem could not be more dif-ferent from that of the binary-star problem. In the nuclear prob-lem, a typical distance (or characteristic length scale) is on the or-der of 10−15 m, whereas in the gravitational context it was 10+11

m - an incredible difference of 26 orders of magnitude. With thischange in spatial scale come other difference, such as in characteris-tic mass and time. In short, we are now dealing with vastly smallerlengths, vastly tinier masses, and vastly shorter times. Luckily forus, VPython can handle all of these changes very well.

Figure 7.2 shows the new setup for the nuclear context.1 The firstthing we notice is the new scene.range which catapults us into themicrocosm. Next we define the nucleus and its properties of mass,charge and momentum.

In Line 13, we introduce the so-called impact parameter, b. This willbe an important control parameter for us to vary from run to run.This parameter tells us, roughly speaking, by how much the alpha-particle would miss the nucleus if it felt no repulsive force. Thus,b = 0 corresponds to a perfectly head-on collision.

Next, we define the alpha particle and its properties of mass, chargeand momentum. Notice that we give the alpha particle some ini-tial speed to the right. In fact, this initial speed is quite large,v0 = 5 × 107 m/s, about 17 percent of the speed of light. We needlarge speeds for the alpha particle to get close to the gold nucleus.This initial speed is another parameter we will be able to adjust later.

Line 22-25 set up arrows for the momenta of the two particles (alpha

1This code is loosely based on the code by R. Chabay, “03-particle collision”, available in theMatter-and-Interactions’s Glowscript-programs folder.

54

Page 64: VPython for Introductory Mechanics: Complete Version

7.4 Simulating the Rutherford experiment 55

Figure 7.2: Setting up the Rutherford-scattering code

and Gold nucleus) and the total momentum. In order to see thesearrows on the screen, they have to be stretched by the scale-factor,scale.

Finally, we have added here for the first time a start-pause button,which will allow us to start the code and pause it at any time. Thedetails of this section of code need not concern us here.

The main part of the code, namely the WHILE loop, is shown in Fig-ure 7.3. We should recognize large chunks of it from before. Lines52 to 55 are new. They will update the momentum vectors through-out the interaction of the two particles. The lengths and direction ofthe three momenta (alpha, nucleus, and total) are set via the .axisassignment. Additionally, we have displaced the tail of the momen-tum vector associated with the nucleus to coincide with the head of

55

Page 65: VPython for Introductory Mechanics: Complete Version

56 Chapter 7 Conservation of Momentum and Energy

the alpha’s momentum vector. This way we can verify visually thatthe two individual momentum vectors do indeed add to the same to-tal momentum vector (via the head-to tail method of adding vectors).

Figure 7.3: The core of the Rutherford-scattering code

7.5 Exercises

• Run the code and observe the trajectories of the two par-ticles. Also observe the particle’s momentum vectors inthe upper-right corner. You should see something like this:

56

Page 66: VPython for Introductory Mechanics: Complete Version

7.5 Exercises 57

• Verify that the momentum vectors are in fact tangentiallyparallel to the trajectory at any given instant of time. Why isthe red arrow so large if the gold nucleus seems to move soslowly?

• Given the vector diagrams rendered in the upper-rightcorner of the screen, is momentum conserved throughout thescattering process? How do you know?

• Adjust the impact parameter, b. Make it progressivelysmaller (all the way to zero) and observe what happens to thedeflection angle of the alpha particle.

• Now make b incrementally bigger than the value in Figure7.2. What do you see now? Is momentum still conserved?

• You can now explore the role of the initial speed of the alphaparticle. How does the angle of deflection seem to depend onthis initial speed?

57

Page 67: VPython for Introductory Mechanics: Complete Version

58 Chapter 7 Conservation of Momentum and Energy

58

Page 68: VPython for Introductory Mechanics: Complete Version

Rotational Motion, Torque, andAngular Momentum

In the previous chapters you saw how a binary star system or acomet can be simulated in VPython. In this chapter, we will reviewthe motion of a comet, and explore torque and angular momentum.The physics of a binary star system and a Sun-comet system areexactly alike. As a matter of fact, the same physics governs anygravitational interaction (in a classical mechanics sense): a clusterof stars, a moon and its planet, or a cluster of galaxies.

8.1 The Physics

Recall Newton’s Law of Universal Gravitation:

F⃗ = −GMm

r2 r̂ (8.1)

(Note this looks similar to Equation (7.4), the Coulomb’s Law forcebetween two charges).

Note that the direction of the position unit vector r̂ is always point-ing in the exact opposite direction (because of the minus sign) of theforce vector.

Angular momentum (symbol L⃗), is the physical quality that is therotational equivalent of linear momentum. Remember that linearmomentum p⃗ = mv⃗. Angular momentum L⃗ = Iω⃗, where I is themoment of inertia, and ω⃗ we encountered way back in Chapter 3 - itis called the angular velocity. Torque (symbol τ⃗ ) can be thought ofas the rotational equivalent of force. It is determined from the cross

Page 69: VPython for Introductory Mechanics: Complete Version

60 Chapter 8 Rotational Motion, Torque, and AngularMomentum

product r⃗ and F⃗τ⃗ = r⃗ × F⃗ (8.2)

Equation (8.2) shows that the torque is the cross product of theposition vector r⃗ and the force applied F⃗ . The cross product is avector. Remember that the magnitude of the cross product here is

|r⃗||F⃗ | sin θ,

where θ is the angle between r⃗ and F⃗ . Its direction is perpendicularto both of the two vectors in the cross product. Here, therefore, thetorque τ⃗ is perpendicular to both r⃗ and F⃗ .

It is very easy to program the cross product in VPython. To calculatethe cross product of A⃗ and B⃗, one uses the command

cross(A,B)

Remember that A and B must have been declared to be vectors inVPython. VPython will know automatically that the value assignedto cross(A,B) is a vector implicitly.

Just as force is the change of linear momentum with respect to time,see Equation (7.3), torque is the change of angular momentum withrespect to time:

τ⃗ = dL⃗

dt(8.3)

Furthermore, just as linear momentum is conserved in the absenceof an outside force, angular momentum is conserved in the absenceof an outside torque. Note that this follows from Equation (8.3).

Look back at Equation (8.1). Recalling that the unit vector r̂ is ro-tated 180◦ from F⃗ , what is the value of τ⃗?

60

Page 70: VPython for Introductory Mechanics: Complete Version

8.2 Exercises 61

Figure 8.1: Program for Comet Orbiting the Sun

Because τ = 0, then L⃗ must be conserved.

See the sample program and output in Figure 8.1.

8.2 Exercises

• Add to the code in Figure 8.1 to calculate the torque and plotit (remember it is a vector and you can print the componentsof a vector!).

61

Page 71: VPython for Introductory Mechanics: Complete Version

62 Chapter 8 Rotational Motion, Torque, and AngularMomentum

Is it pointing in the correct direction?Show that the program is calculating a torque that is closeto the correct answer (it may not, due to limitations in howprecisely VPython does calculations).

• Write code to calculate the angular momentum and plotit. Is it pointing in the correct direction? Print the angularmomentum with every iteration. What do you notice? Doesit make sense?

• Why is the Sun not appearing to move?

• Change the parameters of the program to illustrate anotherscenario (for example, the Earth revolving around the Sun).Discuss what you see.

62

Page 72: VPython for Introductory Mechanics: Complete Version

Two Capstone Projects

9.1 The Gravitational “Slingshot”

In the previous chapters of this book you have gone from investigat-ing the simple motions of an object with constant velocity to explor-ing the physics of a comet about the Sun. While these phenomenaare “real life”, we want to end with a consideration and discussion ofa truly “Space Age” phenomenon that is used regularly in sendingspace probes to the outer solar system – gravitational assist, orthe “slingshot” maneuver.

The outer planets – Jupiter, Saturn, Uranus, and Neptune – as wellas the objects in the Kuiper Belt – including Pluto, Makemake, and2014 MU69 – are extremely far away. Jupiter is just over 5 astro-nomical units1 away from the Sun, Neptune is 30 a.u. away fromthe Sun, and Pluto is 40 a.u. away from the Sun. Traveling to any ofthese objects will take several years to get there.

But how to get there? Traveling directly away from the Sun to ar-rive at a distant planet would take an extraordinary amount of fuelto travel – and that extra fuel means more mass, and the more mass,the more fuel needed. It would be extremely costly, and at this writ-ing we do not have the technology to develop rockets to transporta space probe those distances. The Hohmann orbit (least energymethod) saves on fuel, but takes quite a while to complete the jour-ney.

Gravitational assist allows a space probe to take some of the energyfrom a nearby planet and use it for itself. The energy is “free”!

1An astronomical unit is the average distance of the Earth to the Sun. It is equal to 1.50×108

kilometers.

Page 73: VPython for Introductory Mechanics: Complete Version

64 Chapter 9 Two Capstone Projects

9.1.1 The Physics

The slingshot maneuver involves a planet and a space probe. Bothobjects have a velocity (therefore, both a speed and a direction).When the probe nears the planet and is appreciably affected by theplanet’s gravity, it accelerates (both in speed and direction). Theinteraction is a “collision”, but generally nothing collides. Further-more, the collision is elastic, so therefore there is no loss of energy(and, of course, no change of total momentum) in the planet-probesystem.

So, if the kinetic energy of the probe increases, then the kinetic en-ergy of the planet decreases. The planet slows down! However, theamount of decrease of kinetic energy is negligible to the planet, be-cause the mass of a planet is huge compared to the mass of a spaceprobe. For example, themass of Uranus or Neptune is approximately1026 kg, compared to the mass of a space probe, which is typicallyon the order of 103 kg.

In the rest frame of the Sun, the Sun “sees” the planet moving withinitial velocity U⃗i. The space probe is moving with initial velocityv⃗i. The two objects are not necessarily going to meet head-on; thatwould certainly result in the loss of the spacecraft. Instead, theirvelocity vectors are separated by a distance b, called the impactparameter. If b ≤ the radius of the planet Rp, then there wouldbe a head-on collision.

Consider a planet and a space probe. In the Sun’s frame of reference,the probe has velocity v⃗ and the planet has velocity U⃗ (see Figure9.1). Therefore the probe’s kinetic energy is 1

2mv2. In the planet’sframe of reference, the planet sees the probe approach with speedv + U . As it gets closer, the speed of the probe increases, and afterthe encounter, the probe’s speed decreases until it appears to theplanet to have a speed v + U again, as shown in Figure 9.2. (We are

64

Page 74: VPython for Introductory Mechanics: Complete Version

9.1 The Gravitational “Slingshot” 65

Figure 9.1: Space Probe Approaching Planet

65

Page 75: VPython for Introductory Mechanics: Complete Version

66 Chapter 9 Two Capstone Projects

Figure 9.2: Space Probe After Experiencing Gravitational AssistFrom Planet

assuming an ideal encounter that causes the probe to make a 180◦

change of direction). Therefore, in the Sun’s frame of reference, itappears as if the probe has speed v + 2U .

In the Sun’s frame of reference, then, the kinetic energy of the probeis 1

2m(v + 2U)2.The increase of energy to the probe is 2mU(v+U).(By the same token, because the energy is conserved in this elasticcollision, the planet’s kinetic energy goes down by the same amount,but the change is negligible for the planet).

Several probes to the outer Solar System have used gravitationalassist. They include the Cassini mission to Saturn (see Figure 9.3),the New Horizons mission to Pluto and 2014 MU69, and the famous

66

Page 76: VPython for Introductory Mechanics: Complete Version

9.1 The Gravitational “Slingshot” 67

Figure 9.3: Trajectory of the Cassini Mission to Saturn (source:NASA)

probes Voyager 1 and 2, which are now in interstellar space.2

9.1.2 The Code

In Figure 9.4 the kinetic energies of the probe and the planet arecalculated (e.g., in line 11) as p2

2m , which is the same as 12mv2. In line

27, the gravitational force is calculated, and lines 34 and 35 updatethe planet’s and the probe’s positions at each instant.

2Voyager 1, launched in 1977, is now almost 150 a.u. from the Sun and is the farthest human-made object in existence.

67

Page 77: VPython for Introductory Mechanics: Complete Version

68 Chapter 9 Two Capstone Projects

Figure 9.4: Sample Code for Gravitational Assist

68

Page 78: VPython for Introductory Mechanics: Complete Version

9.1 The Gravitational “Slingshot” 69

9.1.3 Exercises

1. • Run this program to make sure it works. Describe whatyou see.

• Modify the code to incorporate an impact parameter, b.• What happens when you change the impact parameter,to make it larger or smaller?

• What happens when you change the velocities ofthe probe or the planet? In particular, what happensto the speed of the probe when the planet’s velocity is 0?

• Similarly, what happens when the planet’s velocitychanges sign? In that scenario, the probe and the planetare initially moving in the same general direction, withthe probe catching up to the planet.

2. • Now that you have explored the b-dependence a bit,let’s make this a bit more precise. Choose five differentimpact parameters and keep track of the angle ofdeflection of the probe for each. Enter the values forb and deflection angle into a spreadsheet and plot therelationship between those variables. If the graph is notclear, go back and add a few more b-values into yourtable.

• For the same b-values that appear in your list, writedown the the change in kinetic energy of the probe, ex-pressed as a fraction of the initial kinetic energy, basedon the code output. Then enter these values for frac-tional change in kinetic energy into your spreadsheetand plot its dependence on impact parameter.

69

Page 79: VPython for Introductory Mechanics: Complete Version

70 Chapter 9 Two Capstone Projects

Based on this plot, if we want a large increase in kineticenergy for the probe, what do we have to do?

9.2 Asteroid near a Binary Star System -Chaotic orbits, or the “Three-BodyProblem”

In the previous chapters you have gone from investigating the sim-ple motions of an object with constant velocity to exploring thephysics of a comet about the Sun. In all of these examples, themotion did not exhibit what physicists call deterministic chaos. Inthe gravitational problem of two bodies attracting one another, solu-tions can, in fact, be found by pencil and paper. Interestingly, whenwe add a third body all bets are off. The orbits can no longer be pre-dicted with a mathematical formula, but worse than that, the orbitsexhibit what is known as extreme sensitivity to initial conditions - ahallmark of chaos.

9.2.1 Modifying a previous code

To keep things as simple as possible, let us revisit an earlier problem- the binary-star system in Section 7.1. The question we want toask now is: if we introduced a small asteroid into this system howwould it move under the influence of the gravitational attraction toeach star? To make the problem even simpler, we assume that theasteroid is so small that it does not affect the motion of the two stars.Since it is 8 orders of magnitude (or 100 million times) less massivethan the stars, this is a very good approximation. In that case, themass of the asteroid really doesn’t enter into the picture. All we needto do is to calculate the acceleration experienced by the asteroid at

70

Page 80: VPython for Introductory Mechanics: Complete Version

9.2 Asteroid near a Binary Star System - Chaotic orbits, or the“Three-Body Problem”

71

every time step, and this is given by the universal law of gravitationas,

a⃗ = −Gm1r2

1r̂1 − G

m2r2

2r̂2, (9.1)

where r⃗1 is the vector from first star to the asteroid, and r⃗2 is thevector from the second star to the asteroid, and the m’s in the nu-merator are the star masses.

Once we have computed the accelerations, we can update the aster-oid velocity, and then we use the updated velocity to find the nextposition of the asteroid, in a recursive procedure outlined in Chapter6.

So here is the idea. Let us start with the code in Figure 7.1 whichwill take care of the motion of the two stars. To give us a little more“room”, let’s start these two stars out along the x-axis at -5e11 and+5e11 (instead of ±2e11. Also, to keep the center of mass of thesystem fixed, let’s adjust the y-component of the small start from-1e4 to -9e3. Finally, turn off the trails on these two stars, and deleteall calculations of the center of mass (we won’t need that anymore).This takes care of the binary-star system.

Now let’s introduce the asteroid. Add a line defining this objectnear the top that defines the asteroid as a sphere. Give it an initialposition of vector(1.50e12,0,0). Then define a asteroid ve-locity as one of its attribute asasteroid.v = vector(0,-7.5e3,0).

Now that we have defined the asteroid and its initial position andvelocity, we need to turn our attention to its motion. At the end ofthe while-loop, add two lines that compute the vectors r⃗1 and r⃗2,appearing in Equation 9.1. Each of them are just the differences inthe position vectors of the asteroid and the respective star. Withthese two vectors in hand, we can compute the asteroid’s accelera-tion, asteroid.a, using Equation 9.1 directly.

71

Page 81: VPython for Introductory Mechanics: Complete Version

72 Chapter 9 Two Capstone Projects

Figure 9.5: A rudimentary adaptive time step

This program would now run, but it is a good idea to add two morethings. The first one is straightforward. If the asteroid comes tooclose it burns up in the stellar atmosphere. So we should include anif-statement to terminate the program if the asteroid comes within,say, 2e9 (or 2 million kilometers) of either star.

The second refinement has to do with the computational integrationtechnique itself. Right now we are using a simple Euler-Cromer al-gorithm, as explained before. But you may have noticed that whenthe asteroid gets really close to either star, the dynamics is no longersmooth. The asteroid picks up so much speed that it covers a signifi-cant amount of space between successive time steps. In other words,the computational time interval, dt, seems to be too large, and theresult is no longer accurate.

In a more advanced course, you would now probably be learningabout the Runge-Kutta algorithm with an adaptive time-step. Butthat would go beyond the scope of this course. So, instead, let’s im-plement a most rudimentary version of an adaptive time-step. Thebasic idea is that when the asteroid comes within a certain radius ofeither star, then we need to compute more finely by reducing the dt.

Figure 9.5 shows one simple way we can accomplish this. Keep in

72

Page 82: VPython for Introductory Mechanics: Complete Version

9.2 Asteroid near a Binary Star System - Chaotic orbits, or the“Three-Body Problem”

73

mind, however, that this is not a highly accurate algorithm either,and that there aremuchmore sophisticatedways to do this out there.Nonetheless, it improves on our previous method.

9.2.2 Exercises

Now that you have completed the coding, let us have fun and runthe program with a few initial conditions. You should get outputlike the following:

One thing that is immediately clear is that the orbits are highly ir-regular and non-periodic. Furthermore, what you can do is to varythe initial position of the asteroid slightly. For instance, you cancheck the orbits that result from a initial x-coordinate of 1.49, 1.50,and 1.51 × 1012 meters.

Find initial conditions that lead to the three possible long-term out-comes for the asteroid: (a) it crashes into one of the stars, (b) it

73

Page 83: VPython for Introductory Mechanics: Complete Version

74 Chapter 9 Two Capstone Projects

escapes the binary-star system and drifts further and further intospace, and (c) it settles into a semi-stable orbit around one of thestars.

74

Page 84: VPython for Introductory Mechanics: Complete Version

Conclusion

We hope that the previous chapters helped you learn the material inyour introductory physics textbook a little better by giving you theopportunity to explore and play with the ideas in a concrete way.We also hope that these exercises made you appreciate the power ofscientific computation. It can be an invaluable tool in finding andvisualizing solutions and also in helping us build up our physicalintuition and our conceptual understanding of physics.

We encourage you to use the sample codes provided in this bookas a springboard for developing your own codes. These programsare pretty barebones and could be embellished in numerous ways.More importantly, we hope that you use the tools you have acquiredto simulate your own favorite physical processes. Play around withthe code! Tinker with it, and see what happens!

Keep VPython in mind also for the second semester of your intro-ductory physics sequence. There should be plenty of chances to useit for, say, visualizing electric and magnetic fields and so on. Infact, there are a number of excellent sample programs already onthe glowscript.org platform. Additional programs and resources canbe found at multiple online repositories.1

Finally, if you think you want to pursue the physics major, remem-ber VPython can come in handy for your upper-level physics course-work. At that time, it is likely that you have become more familiarwith scientific computing and may be comfortable using the Pythonprogramming language. You can choose from a number of excellent

1see, for instance:https://vpython.org/contents/contributed.htmlhttps://bphilhour.trinket.iohttps://phys221.wordpress.com/vpython-tutorials/

Page 85: VPython for Introductory Mechanics: Complete Version

76 Chapter 10 Conclusion

recent textbooks on computational physics using Python.2 In fact,we consider VPython an excellent gateway into the broader worldof computational physics and scientific computing.

2For instance:R.H. Landau and M.J. Páez, Computational Problems for Physics: With Guided SolutionsUsing Python (CRC Press, 2018).J.M. Kinder and P. Nelson, A Student’s Guide to Python for Physical Modeling (PrincetonU. Press, 2018).M. Newman, Computational Physics (2013).

76

Page 86: VPython for Introductory Mechanics: Complete Version

Bibliography

R. Chabay, B. Sherwood,Matter and Interactions (JohnWiley & Sons,2015).

R. Chabay, B. Sherwood, “Computational Physics in the introduc-tory calculus-based course,” Am. J. Phys. 76, 307 (2008).

A. Cromer, “Stable solutions using the Euler Approximation,” Amer-ican Journal of Physics, 49, 455 (1981).

J.M. Kinder and P. Nelson, A Student’s Guide to Python for PhysicalModeling (Princeton U. Press, 2018).

R.H. Landau and M.J. Páez, Computational Problems for Physics:With Guided Solutions Using Python (CRC Press, 2018).

P. Laws, Workshop Physics Activity Guide, Mechanics, Module 1 and2 (Wiley, 2004).

L.C. McDermott, “A View from Physics” in Toward a Scientific Prac-tice of Science Education (Lawrence Erlbaum Assoc., 1990).

M. Newman, Computational Physics (2013).

E.F. Redish and J.M. Wilson, “Student programming in the introduc-tory physics course,” Am. J. Phys. 61, 222 (1993).

D. Schroeder, Physics Simulations in Python (2018).

D. Sokoloff, R.Thornton, P. Laws, RealTime Physics - Active Learning

Page 87: VPython for Introductory Mechanics: Complete Version

78 Chapter 10 Conclusion

Laboratories (John Wiley & Sons, 2012).

A. Van Heuvelen, “Learning to think like a Physicist: A review ofresearch-based instructional strategies,”Am. J. Phys. 59, 891 (1991).

78

Page 88: VPython for Introductory Mechanics: Complete Version

Authors

Windsor A. Morgan, Jr. is an Associate Professor of Physics &Astronomy at Dickinson College. He specializes in astronomy edu-cation research, and has also done research in X-ray-emitting activegalactic nuclei, X-ray binary star systems, new statistical methods ofstudying astronomical surveys, and the formation of hydrocarbonsin the early solar system.

Lars Q. English is a Professor of Physics at Dickinson College.His research explores “the nonlinear dynamics of complex systems”where both nonlinearity and lattice/network geometry play impor-tant roles in enabling and guiding processes of spontaneous patternsformation. Other interests include the Calculus of Variations, mag-netism and spin resonance, microwave spectroscopy, medical imag-ining techniques, and issues within the philosophy of science. Visit:http://www.larsenglish.com

Page 89: VPython for Introductory Mechanics: Complete Version