Physics Simulations In Python

7m ago
7 Views
0 Downloads
1.51 MB
85 Pages
Transcription

Physics Simulations in PythonA Lab ManualDaniel V. SchroederPhysics DepartmentWeber State UniversityMay 2018

Copyright c 2018, Daniel V. Schroeder.Adapted from Physics Simulations in Java, copyright c 2005–2011.This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/ or send a letter to Creative Commons, PO Box 1866,Mountain View, CA 94042, USA.You can obtain the latest version of this manual at http://physics.weber.edu/schroeder/scicomp/. There you can also find the LATEX source and figurefiles, to facilitate adapting this manual to different needs.

ContentsPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ivProject 1: Making Shapes . . . . . . . . . . . . . . . . . . . . . 1Project 2: Projectile Motion . . . . . . . . . . . . . . . . . . . 11Project 3: Pendulum . . . . . . . . . . . . . . . . . . . . . . . 25Project 4: Orbits . . . . . . . . . . . . . . . . . . . . . . . . . . 35Project 5: Molecular Dynamics . . . . . . . . . . . . . . . . . . 47Project 6: Random Processes . . . . . . . . . . . . . . . . . . . 61Project 7: Final Project . . . . . . . . . . . . . . . . . . . . . . 73iii

PrefaceIntroductory physics courses are full of simplifications: projectiles fly without airresistance, pendulums swing only at small angles, orbits are always circular, andno more than two particles move at any time. These kinds of simplifications arenecessary and appropriate when you’re first trying to understand the basic laws ofnature. But the real world is far more complex, and far more interesting. Becausethe ultimate goal of physics is to understand the real world, students deserve acourse that applies the laws of physics to more complex situations.Fortunately, modern electronic computers make it possible to perform extremelylengthy calculations in a negligible amount of time. These days, therefore, computers offer the best avenue toward applying the basic laws of nature to complexand realistic physical systems. A computer program that models the behavior ofa physical system is called a computer simulation. Creating and using computersimulations is an integral part of modern science and engineering.This manual is intended for a hands-on introductory course in computer simulations of physical systems, using the Python programming language. The goals ofthe course are as follows: Learn enough of the Python language and the VPython and matplotlib graphics packages to write programs that do numerical calculations with graphicaloutput; Learn some step-by-step procedures for doing mathematical calculations (suchas solving differential equations) on a computer; Gain a better understanding of Newton’s laws and other physical principles; Study a variety of physical systems that are too complex for simple penciland-paper calculations, and see what sorts of behavior emerge in such systems.PrerequisitesBefore working through the projects in this manual you should have completed asemester of introductory physics, covering Newton’s laws of motion, conservationprinciples, and a bit of thermodynamics. You should also have taken at least onesemester of calculus. Prior expertise in writing computer programs is not required,but you should be fairly comfortable using a web browser, word processor, andspreadsheet, and you should have some experience at being careful with computersyntax (in any programming language).iv

PrefacevRequired materialsNaturally, you’ll need a computer. The first five projects use a cloud-based versionof Python called GlowScript, so for those you can use any computer with an internetconnection and a modern web browser. (A tablet device without a physical keyboardis not adequate.) For Project 6, you may need to install a free version of the Pythonlanguage and environment (if you’re not using a computer on which it is installedalready).Your GlowScript programs will be automatically saved on Google’s servers, butfor any other files you’ll need to use either some other type of cloud storage or aUSB memory stick for backup.A pocket calculator (perhaps on your mobile phone) will sometimes come inhandy.Finally, you’ll need a few low-tech materials such as scratch paper, pencils, anda small three-ring binder to hold this manual.How to use this manualThis manual is divided into six main chapters, corresponding to six separate projects.In each project you will write a computer program or (more often) a small numberof closely related computer programs. Rather than giving you complete programs torun, the project instructions will provide only code fragments and general guidelineson how to write your programs. This way, once you have completed each program,it will be yours.As you create your computer programs, you will inevitably have questions andencounter difficulties. While you should try to think things through for yourselfwhenever possible, don’t spend too much time being stuck and getting frustrated.Ask your instructor or your lab partner or your other classmates for help. This isnot a test.Exercises and questions will be sprinkled among the instructions in this manual,with space for you to write your answers. Please make every effort work eachexercise and answer each question immediately, before you read on.The general premise of this manual is that you’ll learn more by trying something than by reading a comprehensive explanation of it. Computer languages arelike ordinary languages in this respect: We normally learn new words by hearing,reading, and using them in context, not by studying a dictionary. But if you wantto see a term clearly defined, feel free to ask your instructor or look it up online.Computer programming is fun because it’s so open-ended. You’ll constantlythink of things to try that go beyond the explicit instructions. By all means, tryanything you want! If you’re not sure how to add a certain feature to one of yoursimulations, or if you’re not sure whether it’s practical to do so within a limitedamount of time, be sure to ask your instructor.When you finish a project, gather the instruction pages and staple them togetherwith any printed output from your programs. This stapled packet, together with

viPrefacethe source code of your computer programs, will be your “lab report.”What this manual is notThis manual is not a comprehensive introduction to the Python programming language. Many features of the language are not needed for the types of simulationswe’ll be doing, so we’ll ignore them. Several other features will be used once ortwice but never fully explained.Standard distributions of Python come with dozens of packages (libraries) forcarrying out a wide variety of common tasks. This manual will describe only a tinyfraction of them.At some point you might want to distribute your “finished” VPython programsas web apps or stand-alone applications. This manual won’t tell you how to do that.I’ve tried to design the examples in this manual to illustrate good programmingpractices that are appropriate to the relatively small scale of the projects. This isnot a treatise on the principles of professional software design.This manual is not a textbook on numerical analysis, nor is it a reference workon numerical algorithms. We’ll try out just a few algorithms, make some crudecomparisons, and leave it at that.The projects in this manual touch on some fascinating fields of physics, includingnonlinear dynamics, celestial mechanics, and phase transformations. But this is nota textbook on any of these subjects.Perhaps most importantly, this manual is not intended to be of any use whatsoever to someone who merely reads it without actually working through all of theprojects and exercises.Why Python, VPython, and GlowScript?Choosing a computer programming language always involves trade-offs. Fortunately, there are more choices today than ever before.An obvious choice for this course would be one of the traditional computerlanguages like Fortran, C, or C . These languages are widely used for scientific computation due to their flexibility and speed. The languages are defined bystandards committees rather than by commercial vendors, and free versions areavailable. However, they have grown somewhat complex over the years, as featureshave been added while maintaining compatibility with older versions. Another disadvantage is that none of these languages include built-in support for graphics, andadd-on graphics libraries tend to be difficult to install and use.The Basic programming language was specifically designed to be easy to learn,and current versions of Basic have kept this feature. Because Basic is widely usedby students and hobbyists, all modern versions include built-in, easy-to-use graphics support. Some versions (True Basic and Xojo) are cross-platform, but the mostwidely used version, Microsoft’s Visual Basic, runs only on the Windows operating

Prefaceviisystem. The fragmentation of Basic into multiple versions, each with its own idiosyncracies, is a major disadvantage. Programs written in Basic also tend to runrather slowly. Most versions of Basic are sold commercially, though the prices aregenerally reasonable.For mathematical calculations, the most convenient choice is often a specializedmathematical programming environment such as Mathematica (which I use a greatdeal), Maple, or Matlab. These packages contain sophisticated, speedy, built-inroutines for a great variety of mathematical tasks, but their high overhead canmake them rather slow and awkward when you need to program a custom step-bystep algorithm. Because they are commercial products aimed at relatively narrowmarkets, these packages tend to be expensive. (However, there is a free productcalled Octave that is very similar to Matlab.)An earlier version of this manual used the Java programming language, introduced by Sun Microsystems (now Oracle) in 1995. Although based on C and C ,Java is easier to learn and use, and comes with standard cross-platform libraries forgraphics and other common tasks. Its computational performance is remarkablygood, though it isn’t as fast as C or C or Fortran. But Java never really caughton with scientists, and its early use for web-delivered “applets” has now become obsolete. More importantly for us, programming in Java requires some inconvenientsoftware installations and learning to use some rather advanced object-oriented features that are really superfluous in a first course in scientific computing.For web-delivered applications, Java has now been replaced by JavaScript, arather different language that was deliberately named to emphasize their superficialsimilarities. Every modern web browser can run JavaScript programs, and you’rerunning them constantly as you surf the web. Writing JavaScript programs is anatural extension of creating ordinary web pages. Moreover, in recent years, thecomputational performance of the JavaScript engines in the most widely used webbrowsers has nearly matched that of Java, which in turn isn’t far behind C (etc.).The main disadvantage of JavaScript is that for practical purposes it runs only ina web browser, so for security reasons it cannot access your computer’s file system.This restriction has limited its use by scientists, at least for serious computationalwork.Python is a relatively new, free, cross-platform language that scientists are usingmore and more widely. It is a simple language to get started with, and developersare creating a growing assortment of add-on packages to make various difficult tasksfairly easy. These add-on packages include several for numerical calculations andscientific graphics. One big disadvantage of Python is that every Python installation is a little different, depending on which Python version and add-on packagesare present. Getting someone else’s Python program to run on your Python systemcan therefore be a frustrating task. Another disadvantage is that most Python interpreters do not produce very efficient machine code, so Python programs tend torun rather slowly—necessitating the use of add-on packages for heavy-duty computation. Finally, a disadvantage for this course is that none of the graphics packages

viiiPrefaceincluded in the more common Python installations are especially convenient forcreating animated graphics or interactive user controls.The VPython (short for Visual Python) package is an attempt to address thislast deficiency. It provides a very easy interface to a 3D graphics library, alongwith some auxiliary functions for handling vectors and animation. It was createdspecifically for use in undergraduate physics courses, and it is being maintainedand improved by Bruce Sherwood, a physics teacher and textbook author. Unfortunately, the VPython package has never been a standard part of most Pythoninstallations, and its graphics systems have not always worked well with all Pythonenvironments. The difficulty of installing VPython and getting it to work correctlyhas therefore been a barrier to its use.More recently, though, Sherwood and others have created GlowScript: a cloudbased environment for writing and running 3D graphics programs in a web browser.Originally GlowScript required programming in JavaScript, but now it has a builtin facility for translating Python code into JavaScript behind the scenes, so to theprogrammer it appears very similar to VPython. GlowScript-VPython thereforeoffers most of the advantages of VPython, without any of the installation hassles.And it runs significantly faster than Python in most cases, because the JavaScriptengines in modern web browsers are so good. The disadvantages of this environmentare mostly the same as those of JavaScript: A GlowScript program cannot directlyaccess your computer’s file system, and (for the same reason) it does not have accessto the vast world of Python add-on packages. (The common math functions and afew other essential functions