A Student’s Guide to Python for Physical Modeling Second Edition A Student’s Guide to Python for Physical Modeling Second Edition Jesse M. Kinder and Philip Nelson PrincetonUniversityPress PrincetonandOxford Copyright©2015,2018,2021byPrincetonUniversityPress. Allrightsassociatedwiththecomputercodeinthisworkareretained byJesseM.KinderandPhilipNelson. PrincetonUniversityPressiscommittedtotheprotectionofcopyrightandtheintellectualpropertyour authorsentrusttous.Copyrightpromotestheprogressandintegrityofknowledge.Thankyoufor supportingfreespeechandtheglobalexchangeofideasbypurchasinganauthorizededitionofthisbook. Ifyouwishtoreproduceordistributeanypartofitinanyform,pleaseobtainpermission. Requestsforpermissiontoreproducematerialfromthiswork [email protected]. PublishedbyPrincetonUniversityPress,41WilliamStreet, Princeton,NewJersey08540 IntheUnitedKingdom:PrincetonUniversityPress,6OxfordStreet, Woodstock,OxfordshireOX201TR press.princeton.edu AllRightsReserved OriginaleditionpublishedbyPrincetonUniversityPress2015 Updatededitionpublished2018 ISBN978-0-691-21928-8 ISBN(e-book)978-0-691-22366-7 ISBN(pbk.)978-0-691-22365-0 LibraryofCongressControlNumber2021934834. BritishLibraryCataloging-in-PublicationDataisavailable. ThisbookhasbeencomposedusingtheLATEXtypesettingsystem. Thepublisherwouldliketoacknowledgetheauthorsofthisvolumefor providingthecamera-readycopyfromwhichthisbookwasprinted. Printedonacid-freepaper.∞ PrintedintheUnitedStatesofAmerica 1 2 3 4 5 6 7 8 9 10 ThefrontcovershowsaMandelbrotset,animagethatyouwillbeable togenerateforyourselfafteryouworkthroughthisbook. Althoughtheauthorshavesoughttoprovideaccurateandup-to-date information,theyassumenoresponsibilityforerrorsoromissions, noranyliabilityfordamagesresultingfromtheuseoftheinformation contained within this document. The authors make no claim that suggestionsandcodesamplesdescribedhereinwillworkinfuture versionsofPythonoritsextendedenvironments. ForOliverArthurNelson—PN Contents Let’s Go xiii 1 Getting Started with Python 1 1.1 Algorithmsandalgorithmicthinking 1 1.1.1 Algorithmicthinking 1 1.1.2 States 2 1.1.3 Whatdoesa = a + 1mean? 3 1.1.4 Symbolicversusnumerical 3 1.2 LaunchPython 4 1.2.1 IPythonconsole 6 1.2.2 Errormessages 10 1.2.3 Sourcesofhelp 10 1.2.4 Goodpractice:Keepalog 11 1.3 Pythonmodules 11 1.3.1 import 12 1.3.2 from ... import 12 1.3.3 NumPyandPyPlot 13 1.4 Pythonexpressions 14 1.4.1 Numbers 14 1.4.2 Arithmeticoperationsandpredefinedfunctions 14 1.4.3 Goodpractice:Variablenames 15 1.4.4 Moreaboutfunctions 16 2 Organizing Data 19 2.1 Objectsandtheirmethods 19 2.2 Lists,tuples,andarrays 21 2.2.1 Creatingalistortuple 21 2.2.2 NumPyarrays 21 2.2.3 Fillinganarraywithvalues 23 2.2.4 Concatenationofarrays 24 2.2.5 Accessingarrayelements 25 2.2.6 Arraysandassignments 26 2.2.7 Slicing 27 2.2.8 Flatteninganarray 28 vii viii 2.2.9 Reshapinganarray 28 2.2.10 T2 Listsandarraysasindices 29 2.3 Strings 29 2.3.1 Rawstrings 31 2.3.2 Formattingstringswiththeformat()method 31 2.3.3 T2 Formattingstringswith% 32 3 Structure and Control 35 3.1 Loops 35 3.1.1 forloops 35 3.1.2 whileloops 37 3.1.3 Verylongloops 37 3.1.4 Infiniteloops 37 3.2 Arrayoperations 38 3.2.1 Vectorizingmath 38 3.2.2 Matrixmath 40 3.2.3 Reducinganarray 41 3.3 Scripts 42 3.3.1 TheEditor 42 3.3.2 T2 Othereditors 42 3.3.3 Firststepstodebugging 43 3.3.4 Goodpractice:Commenting 45 3.3.5 Goodpractice:Usingnamedparameters 47 3.3.6 Goodpractice:Units 48 3.4 Contingentbehavior:Branching 49 3.4.1 Theifstatement 50 3.4.2 Testingequalityoffloats 51 3.5 Nesting 52 4 Data In, Results Out 53 4.1 Importingdata 53 4.1.1 Obtainingdata 54 4.1.2 BringingdataintoPython 54 4.2 Exportingdata 57 4.2.1 Scripts 57 4.2.2 Datafiles 58 4.3 Visualizingdata 60 4.3.1 Theplotcommandanditsrelatives 60 4.3.2 Logaxes 63 4.3.3 Manipulateandembellish 63 4.3.4 Replacingcurves 65 4.3.5 T2 Moreaboutfiguresandtheiraxes 65 4.3.6 T2 Errorbars 66 Jump to Contents Jump to Index ix 4.3.7 3Dgraphs 66 4.3.8 Multipleplots 67 4.3.9 Subplots 68 4.3.10 Savingfigures 69 4.3.11 T2 Usingfiguresinotherapplications 70 5 First Computer Lab 71 5.1 HIVexample 71 5.1.1 Explorethemodel 71 5.1.2 Fitexperimentaldata 72 5.2 Bacterialexample 73 5.2.1 Explorethemodel 73 5.2.2 Fitexperimentaldata 73 6 Random Number Generation and Numerical Methods 75 6.1 Writingyourownfunctions 75 6.1.1 DefiningfunctionsinPython 76 6.1.2 Updatingfunctions 78 6.1.3 Arguments,keywords,anddefaults 78 6.1.4 Returnvalues 79 6.1.5 Functionalprogramming 80 6.2 Randomnumbersandsimulation 81 6.2.1 Simulatingcoinflips 82 6.2.2 Generatingtrajectories 82 6.3 Histogramsandbargraphs 83 6.3.1 Creatinghistograms 83 6.3.2 Finercontrol 85 6.4 Contourplots,surfaceplots,andheatmaps 86 6.4.1 Generatingagridofpoints 86 6.4.2 Contourplots 86 6.4.3 Surfaceplots 87 6.4.4 Heatmaps 88 6.5 Numericalsolutionofnonlinearequations 89 6.5.1 Generalrealfunctions 89 6.5.2 Complexrootsofpolynomials 90 6.6 Solvingsystemsoflinearequations 91 6.7 Numericalintegration 92 6.7.1 Integratingapredefinedfunction 92 6.7.2 Integratingyourownfunction 93 6.7.3 Oscillatoryintegrands 94 6.7.4 T2 Parameterdependence 94 6.8 Numericalsolutionofdifferentialequations 95 6.8.1 Reformulatingtheproblem 95 Jump to Contents Jump to Index