Transcription of Modeling and Simulation in Python - Green Tea Press
1 Modeling and Simulation in PythonVersion B. DowneyGreen Tea PressNeedham, MassachusettsCopyright 2017 Allen B. Tea Press9 Washburn AveNeedham MA 02492 Permission is granted to copy, distribute, transmit and adapt this work under aCreative Commons Attribution-NonCommercial-ShareAlike InternationalLicense: you are interested in distributing a commercial version of this work, pleasecontact the LATEX source and code for this book is available Modeling be taught? .. much programming do I need? .. much math and science do I need? .. started .. Python .. my files .. Jupyter .. xvii1 falling penny myth ..42 Bike .. functions .. statements .. statements .. loops ..163 Iterative Modeling .. than one State object .. bikes .. operators ..254 Sweeping that return values .. kinds of parameters .. and arrays .. parameters .. development ..325 World Population Data .. growth model ..406 Modeling objects.
2 Growth model .. out the update function .. birth and death ..487 Quadratic growth ..558 projections .. projections ..629 relations .. equations .. and Simulation .. with WolframAlpha .. with SymPy .. equations in SymPy .. the quadratic growth model ..7310 Case tools .. the hood .. queue or two? .. salmon populations .. growth ..82viCONTENTS11 Freshman Plague .. SIR model .. SIR equations .. update function .. the Simulation .. the results .. with a TimeFrame ..9412 .. washing .. 10413 Sweeping two .. beta .. gamma .. 11014 .. number .. and Simulation .. 11815 coffee cooling problem .. and heat .. transfer .. s law of cooling .. 12516 fsolve .. liquids .. first or last? .. 13617 glucose-insulin system .. glucose minimal model .. 14418 Numerical differential equations .. squares .. parameters.
3 15219 Case tools .. the hood .. insulin minimal model .. Filter .. behavior of a wall .. 16420 s second law of motion .. pennies .. 17221 Air force .. jumping .. acceleration .. 18222 Projectiles in .. baseball flight .. 19223 Manny Ramirez problem .. the range .. off the problem .. 19924 physics of toilet paper .. 20725 acceleration .. of inertia .. and turntables .. friction .. 21626 Case tools .. the hood .. dunk revisited .. a yo-yo .. Can Modeling be taught?The essential skills of Modeling abstraction, analysis, Simulation , and vali-dation are central in engineering, natural sciences, social sciences, medicine,and many other fields. Some students learn these skills implicitly, but in mostschools they are not taught explicitly, and students get little practice. That sthe problem this book is meant to Olin College, we use this book in a class called Modeling and Simulation ,which all students take in their first semester.
4 My colleagues, John Geddesand Mark Somerville, and I developed this class and taught it for the first timein is based on our belief that Modeling should be taught explicitly, early, andthroughout the curriculum. It is also based on our conviction that computationis an essential part of this students are limited to the mathematical analysis they can do by hand, theyare restricted to a small number of simple physical systems, like a projectilemoving in a vacuum or a block on a frictionless they will only work with bad models; that is, models that are too simplefor their intended purpose. In nearly every mechanical system, air resistanceand friction are essential features; if we ignore them, our predictions will bewrong and our designs won t most freshman physics classes, students don t make Modeling decisions;sometimes they are not even aware of the decisions that have been made forthem. Our goal is to teach the entire Modeling process and give students achance to practice 0 How much programming do I need?
5 If you have never programmed before, you should be able to read this book,understand it, and do the exercises. I will do my best to explain everything youneed to know; in particular, I have chosen carefully the vocabulary I introduce,and I try to define each term the first time it is used. If you find that I haveused a term without defining it, let me you have programmed before, you will have an easier time getting started,but you might be uncomfortable in some places. I take an approach to pro-gramming you have probably not seen programming classes1have two big problems:1. They go bottom up , starting with basic language features and gradu-ally adding more powerful tools. As a result, it takes a long time beforestudents can do anything more interesting than convert Fahrenheit They have no context. Students learn to program with no particular goalin mind, so the exercises span an incoherent collection of topics, and theexercises tend to be this book, you learn to program with an immediate goal in mind: writingsimulations of physical systems.
6 And we proceed top down , by which I meanwe use professional-strength data structures and language features right particular, we use the following Pythonlibraries: NumPy for basic numerical computation ( ). SciPy for scientific computation ( ). Matplotlib for visualization ( ). Pandas for working with data ( ). SymPy for symbolic computation, ( ). Pint for units like kilograms and meters ( ).1 Including many I have How much math and science do I need?xiii Jupyter for reading, running, and developing code ( ).These tools let you work on more interesting programs sooner, but there aresome drawbacks: they can be hard to use, and it can be challenging to keeptrack of which library does what and how they have tried to mitigate these problems by providing a library, calledmodsim,that makes it easier to get started with these tools, and provides some addi-tional features in themodsimlibrary are like training wheels; at some point youwill probably stop using them and start working with the underlying librariesdirectly.
7 Other features you might find useful the whole time you are workingthrough the book, and encourage you to read the themodsimlibrary code. Most of it is not com-plicated, and I tried to make it readable. Particularly if you have some pro-gramming experience, you might learn something by reverse engineering mydesign How much math and science do I need?I assume that you know what derivatives and integrals are, but that s aboutall. In particular, you don t need to know (or remember) much about findingderivatives or integrals of functions analytically. If you know the derivative ofx2and you can integrate 2x dx, that will do it2. More importantly, you shouldunderstand what those conceptsmean; but if you don t, this book might helpyou figure it don t have to know anything about differential for science, we will cover topics from a variety of fields, including demogra-phy, epidemiology, medicine, thermodynamics, and mechanics. For the mostpart, I don t assume you know anything about these topics.
8 In fact, one of theskills you need to do Modeling is the ability to learn enough about new fieldsto develop models and if you noticed that those two questions answer each other, even 0 PrefaceWhen we get to mechanics, I assume you understand the relationship betweenposition, velocity, and acceleration, and that you are familiar with Newton slaws of motion, especially the second law, which is often expressed asF=ma(force equals mass times acceleration).I think that s everything you need, but if you find that I left something out,please let me Getting startedTo run the examples and work on the exercises in this book, you have to:1. Install Python on your computer, along with the libraries we will Copy my files onto your Run Jupyter, which is a tool for running and writing programs, and loadanotebook, which is a file that contains code and next three sections provide details for these steps. I wish there were aneasier way to get started; it s regrettable that you have to do so much workbefore you write your first program.
9 Be persistent! Installing PythonYou might already have Python installed on your computer, but you mightnot have the latest version. To use the code in this book, you need or later. Even if you have the latest version, you probably don t have allof the libraries we could update Python and install these libraries, but I strongly recom-mend that you don t go down that road. I think you will find it easier to useAnaconda, which is a free Python distribution that includes all the librariesyou need for this book (and more).Anaconda is available for Linux, macOS, and Windows. By default, it puts allfiles in your home directory, so you don t need administrator (root) Copying my filesxvto install it, and if you have a version of Python already, Anaconda will notremove or modify Download the installer foryour system and run it. You don t need administrative privileges to installAnaconda, so I recommend you run the installer as a normal user, not asadministrator or suggest you accept the recommended options.
10 On Windows you have theoption to install Visual Studio Code, which is an interactive environment forwriting programs. You won t need it for this book, but you might want it forother default, Anaconda installs most of the packages you need, but there are afew more you might have to add. Once the installation is complete, open acommand window. On macOS or Linux, you can use Terminal. On Windows,open the Anaconda Prompt that should be in your Start the following command (copy and paste it if you can, to avoid typos):conda install jupyterlab pandas seaborn sympy beautifulsoup4 lxmlSome of these packages might already be installed. Then run this command:conda install -c unidata pintThat should be everything you Copying my filesThe code for this book is available , which is aGit repository. Git is a software tool that helps youkeep track of the programs and other files that make up a project. A collectionof files under Git s control is called a repository (the cool kids call it a repo ).