Programming, Modeling and Simulation in Python
PER JÖNSSON
Copying prohibited
This book is protected by the Swedish Copyright Act. Apart from the restricted rights for teachers and students to copy material for educational purposes, as regulated by the Bonus Copyright Access agreement, any copying is prohibited. For information about this agreement, please contact your course coordinator or Bonus Copyright Access.
Should this book be published as an e-book, the e-book is protected against copying.
Any use of this work for text- and/or datamining purposes is prohibited.
Anyone who violates the Copyright Act may be prosecuted by a public prosecutor and sentenced either to a fine or to imprisonment for up to 2 years and may be liable to pay compensation to the author or to the rightsholder.
Studentlitteratur publishes digitally as well as in print formats. Studentlitteratur’s printed matter is sustainably produced, as regards both paper and the printing process.
Art.nr 45430
ISBN 978-91-44-16046-7
Edition 1:1
© The Author and Studentlitteratur 2023
studentlitteratur.se
Studentlitteratur AB, Lund
Cover design by: Jens Martin
Photo cover: CC Wikimedia commons/Brian Gratwicke
Printed by Eurographic Group, 2023
Preface
Thisbookisbasedontheauthor’scoursesinprogramming,modelingand simulation,andcomputationalphysicsatMalmöUniversity.Theprerequisiteisanintroductorycourseinmathematicsatuniversitylevel.Thereader isnotrequiredtohaveanypreviousexperienceinprogramming.
Thebookisdividedintothreeparts.Thefirstpartdealswithprogramming.Allimportantconceptssuchasvariables,datatypes,assignments, if-statements,for-andwhileloops,programstructureandvectorizationare introducedanddiscussed.Thereisalsoachapteronobject-orientedprogramming.Thepowerfulcommandsforgraphicsaretreatedindetail.The presentationisveryhands-onandbasedonconcreteexamples:thisiswhat youwriteandthisiswhatyouget.
Thesecondpartofthebookisdevotedtothemathematicsneededtomodel andsimulate.Inlinearalgebra,vectors,matrices,linearequationsystems, eigenvalues,andeigenvectorsaretreated.Thepresentationconnectstothe built-incommandsandroutinesinPython.Calculusinoneandmoredimensionsistreatedintwochapters.Importantconceptssuchasgraph, continuity,equationsandequationsystems,derivatives,gradients,Taylor expansions,grids,finitedifferenceapproximationsandintegralsaretreated indetail.Again,thepresentationconnectstoPython’sbuilt-infunctions androutines.Plottingandgraphicsareimportantpartsofthepresentation. Symbolicmathematicsistreatedinonechapter,anditisshownhowmany tediouscomputationsbypaperandpencilcanbedonebythecomputer.
Thethirdpartofthebookconcernsmodelingandsimulation.Startingwith anoverviewofmodelingandsimulation,thebookgoesontodescribemathematicalmethodstosetupmodelsandrunsimulations,butalsotohandle andanalyzeobservationsandexperimentaldata.Thedescriptionistoalarge extentbasedonthepackagesNumPy,SciPyandMatplotlib.Thepresentationishands-onwiththeaimtoshowhowPythoncanbeusedto’getthings done’.
©FÖRFATTAREN OCH STUDENTLITTERATUR
Thebookcontainsnumerousexerciseswithcompletesolutions,makingit suitableforselfstudies.Atthebook’swebsite
studentlitteratur.se/45430
therearedatafilesandmaterialstorunalltheexamplesinthebook.At thewebsite,therearealsocomplementarymaterialsandsolutionstoallthe exercisesinthebookintermsofexecutablepy-files.Inaddition,thereare py-filesformanyoftheexamplesinthebook.
Inprogramming,aswellasinmathematics,itisimportantthatbasicknowledgeisautomated(’sitsinthefingers’).Wecanthenfreecognitiveresources toattackandsolveproblemsefficiently.Accordingtotheauthor,thebest waytoautomateprogrammingistositbythecomputerandenterthecommandsandrunthebook’sexamples.Thistakestime,butthistimerepays. Itisalsoimportanttorealizethatonehastodoerrorsinordertolearnnew things.Programmingisoftenveryfrustrating:youhavemadesomemistake andcannotfindtheerror.Don’tgiveup!Whenyouhavefoundtheerror orbug,youhavelearnedsomethingandtakenastepforward.
Chapter22aboutMonteCarlomethodsiswrittenbyassociateprofessor JörgenEkman.IwanttodirectabigthankyoutoJörgenforhisactive contributiontothisbook,aswellasformanyvaluablediscussionsabout modelingandsimulation.
Readersarewelcometoleavecommentsandsuggestionsregardingthebook.
Finally,Iwanttothankmyfamily–Agneta,Björn,Lo,IsabelleandJulia–fortheirsupportduringtheworkwiththisbook.
Malmö,June2023
PerJönsson per.jonsson@mau.se
©FÖRFATTAREN OCH STUDENTLITTERATUR 4
©FÖRFATTAREN OCH STUDENTLITTERATUR Contents IPythonprogramming 15 1IntroductiontoPython 17 1.1InstallingPython........................17 1.2Spyderdevelopmentenvironment...............17 1.3Packagesandmodules......................18 1.4Interactiveruns–Pythonasacalculator...........19 1.5Scriptsandpy-files.......................20 1.6TAB-completion.........................22 1.7Goodtoknowcommands....................23 1.8Variableexplorer–readandwritetofile...........24 1.9LaTeX–documentprograms..................26 1.10Studyquestions.........................27 1.11Exercises.............................28 2Numbersandfunctions 31 2.1Differenttypesofnumbers...................31 2.2Arithmetic............................32 2.3Functionsofrealnumbers....................35 2.4Functionsofcomplexnumbers.................37 2.5Complexnumbers–attributesandmethods.........38 2.6Lambdafunctions........................40 2.7Significantdigitsandcancellation...............41 2.8Studyquestions.........................42 2.9Exercises.............................43 3Datatypes,variables,andassignments 47 3.1Numbers,strings,lists,andtuples...............47 3.2Assignments...........................48 3.3Assignmentsintechnicalterms.................48 3.4Assignments–value,type,andreference...........49 3.5Assignments–stepping.....................51 3.6Tuplesandmultipleassignments................51
©FÖRFATTAREN OCH STUDENTLITTERATUR 6 CONTENTS 3.7Assignmentsofcomplexexpressions..............52 3.8Variablenames..........................53 3.9Readingandwritingtothescreen...............54 3.10Application–replacingwindows................56 3.11Studyquestions.........................57 3.12Exercises.............................58 4Lists,tuplesandstrings 63 4.1Indexationoflists,tuplesandstrings.............63 4.2Slicesoflists,tuplesandstrings................66 4.3Slices–howtothink......................68 4.4Lists–mutability........................69 4.5Listswithnumbers–listcomprehension...........71 4.6Classesandmethods......................73 4.7Methodsforlists.........................74 4.8Methodsforstrings.......................76 4.9Studyquestions.........................80 4.10Exercises.............................81 5Vectors,matricesandmultidimensionalarrays 85 5.1NumPy..............................85 5.2Arrays..............................85 5.3Arrays–attribute........................87 5.4Vectors..............................87 5.5Rangeandlinspace.......................89 5.6Subvectors............................91 5.7Vectors–removingelements..................93 5.8Vectors–mutability.......................93 5.9Matrices.............................95 5.10Zeroandonematrices......................96 5.11Diagonalandbandedmatrices.................97 5.12Randommatrices........................98 5.13Reshapingmatrices.......................100 5.14Rowmatricesversusvectors..................103 5.15Submatrices...........................104 5.16Stackingmatrices........................106 5.17Writingandreadingtofile...................108 5.18Arithmeticoperationsonarrays................112 5.19Element-wisefunctions.....................114 5.20Aggregationandlocalizationfunctions............116 5.21Methodsforndarray.......................120 5.22Application–temperature...................121 5.23Studyquestions.........................124 5.24Exercises.............................125
©FÖRFATTAREN OCH STUDENTLITTERATUR CONTENTS 7 6Graphicsandvisualization 135 6.1Matplotlib–pyplot.......................135 6.2Examplegallery.........................136 6.3Createandsaveafigure.....................137 6.4Basicplotmethods.......................139 6.5Axesandscaling.........................144 6.6Textandlegend.........................148 6.7Arrowsandexplainingtext...................151 6.8Polygonsandfilledareas....................152 6.9Histogramandbarcharts....................153 6.10Plotsoftwo-dimensionalfunctions...............157 6.11Plotmethodsfor3D-graphics..................158 6.12Contourplots..........................162 6.13Implicitfunctions........................165 6.14Matricesandimages.......................167 6.15Animations............................170 6.16Interactionwithimages.....................173 6.17Graphics–generaladvice....................175 6.18Studyquestions.........................176 6.19Exercises.............................177 7Programming 185 7.1Logicalexpressions.......................185 7.2If-statements...........................188 7.3While-loops............................190 7.4For-loops.............................193 7.5Pre-allocation–elementcounter................197 7.6Breakcommandsandflags...................198 7.7Break-loops............................199 7.8Nestedloops...........................201 7.9Application–Madelungconstant...............202 7.10Application–signalprocessing.................204 7.11Application–imageprocessing.................206 7.12Application–heatflow.....................208 7.13Studyquestions.........................209 7.14Exercises.............................210 8Programstructure 225 8.1Program,functions,andmodules................225 8.2Functions.............................226 8.3Functioncalls..........................227 8.4Functions–mutability.....................231 8.5Functions–undefinedlocalvariables.............232 8.6Functionnamesasinputvariables...............233
©FÖRFATTAREN OCH STUDENTLITTERATUR 8 CONTENTS 8.7Differentnumberofinputvariables–keywordarguments..235 8.8Functionscollectedinmodules.................237 8.9Themodulessearchpath....................238 8.10Application–symmetries....................239 8.11Application–areaonthemap.................242 8.12Studyquestions.........................245 8.13Exercises.............................246 9Vectorizationandefficiency 253 9.1Measuringexecutiontime....................253 9.2Vectorization...........................254 9.3Vectorizedoperationsundermasks...............256 9.4Extractingindexesandcounting................258 9.5Application–vectorizedheatflow...............260 9.6Application–digitalimageclassification...........261 9.7Studyquestions.........................263 9.8Exercises.............................264 10Object-orientedprogramming 269 10.1Classes..............................269 10.2Protectingattributes–gettersandsetters..........276 10.3Specialmethods.........................281 10.4Subclasses–inheritance.....................287 10.5Application–functionswithparameters...........291 10.6Studyquestions.........................293 10.7Exercises.............................294 IIComputermathematics 297 11Linearalgebra 299 11.1NumPy–linearalgebra.....................299 11.2Coordinatesystems.......................300 11.3Computationwithvectors...................302 11.4Scalarproduct..........................304 11.5Normalizedvectors.......................305 11.6VectorsinPython........................305 11.7Matrices.............................306 11.8Matrixoperations........................307 11.9Inversematrix..........................310 11.10TransposeandHermitiantranspose..............312 11.11Orthogonalandunitarymatrices................314 11.12SymmetricandHermitianmatrices..............314 11.13Determinants...........................315
©FÖRFATTAREN OCH STUDENTLITTERATUR CONTENTS 9 11.14Linearequationsystems.....................317 11.15Ill-conditionedsystems.....................320 11.16Eigenvaluesandeigenvectors..................323 11.17Numericalmethod–Gaussianelimination..........327 11.18Numericalmethod–eigenvalues................330 11.19Application–dynamicalsystem................332 11.20Application–freeoscillations..................337 11.21Application–forcedoscillations................341 11.22Studyquestions.........................344 11.23Exercises.............................345 12Functionsofonevariable 353 12.1Functionsofonevariable....................353 12.2Functiongraph..........................354 12.3Continuityandzeros......................355 12.4Derivative............................356 12.5Derivativesofhigherorder...................358 12.6Taylorpolynomials.......................359 12.7Maximumandminimum....................361 12.8Grid–finitedifferences.....................362 12.9Finitedifferences–methodofundeterminedcoefficients...365 12.10Integrals.............................368 12.11Thetruncationerrorforthemiddlesum............370 12.12Richardsonextrapolation....................371 12.13Vectorvaluedfunctions.....................375 12.14Application–graphsofderivatives...............377 12.15Application–zeros.......................378 12.16Studyquestions.........................380 12.17Exercises.............................380 13Functionsofseveralvariables 385 13.1Functionsoftwovariables....................385 13.2Domainsintheplane......................386 13.3Functiongraph..........................387 13.4Levelcurves...........................389 13.5Continuity............................390 13.6Derivative............................391 13.7Gradient.............................392 13.8Derivativesofhigherorder...................394 13.9TangentplaneandTaylorpolynomials............395 13.10Maximumandminimum....................397 13.11Grid–finitedifferences.....................399 13.12Doubleintegrals.........................401 13.13Doubleintegralsovergeneraldomains.............403
©FÖRFATTAREN OCH STUDENTLITTERATUR 10 CONTENTS 13.14Functionsof n variables.....................405 13.15Vectorvaluedfunctionsof n variables.............413 13.16Studyquestions.........................415 13.17Exercises.............................416 14Symbolicmathematics 421 14.1SymPy..............................421 14.2Print-outformatsandinteroperability.............422 14.3Computationwithrationalnumbers..............424 14.4Computationwithcomplexnumbers..............424 14.5Symbolicvariables........................426 14.6Algebraicmanipulations–substitutions............427 14.7Linearalgebra..........................429 14.8Functionsofonevariable....................436 14.9Functionsofseveralvariables..................444 14.10Studyquestions.........................448 14.11Exercises.............................449 IIIModelingandsimulation 453 15IntroductiontomodelingandsimulationwithSciPy455 15.1Modelingandsimulation....................455 15.2Advantageswithsimulations..................456 15.3Differenttypesofmodelsandsimulations...........456 15.4Visualizations..........................457 15.5Challenges............................458 15.6SciPy...............................459 15.7Importsubpackages.......................460 15.8Application–changingconditions...............461 15.9Application–epidemiology...................462 15.10Studyquestions.........................464 15.11Exercises.............................465 16Interpolation 467 16.1Polynomials...........................467 16.2Interpolationwithpolynomials.................470 16.3Interpolationwithsplines....................475 16.4Interpolationintwodimensions................477 16.5Interpolationwithperiodicfunctions.............482 16.6DiscreteFouriertransform...................483 16.7Nyquistfrequency........................485 16.8FastFourierTransform(FFT).................486 16.9DiscreteFouriertransformofimages..............489
©FÖRFATTAREN OCH STUDENTLITTERATUR CONTENTS 11 16.10Studyquestions.........................495 16.11Exercises.............................496 17Non-linearequations 501 17.1Non-linearequations.......................501 17.2Systemsofnon-linearequations................502 17.3Conditioning...........................504 17.4Built-infunctionsinPython..................504 17.5Numericalmethods.......................511 17.6Application–Lagrangepoints.................518 17.7Studyquestions.........................520 17.8Exercises.............................520 18Optimization 527 18.1Globalandlocalminima....................527 18.2Univariateoptimization.....................528 18.3Multivariateoptimization....................530 18.4Conditioning...........................532 18.5Built-infunctionsinPython..................532 18.6Numericalmethods–univariateminimization........541 18.7Numericalmethods–multivariateminimization.......546 18.8Application–reconstructionofsurface............550 18.9Studyquestions.........................553 18.10Exercises.............................554 19Modelingofdata 559 19.1Leastsquaresfits........................559 19.2Linearleastsquares.......................560 19.3Polynomialmodelfunctions...................562 19.4Linearmodelfunctions.....................564 19.5Non-linearmodelfunctions...................566 19.6Multivariatemodelfunctions..................570 19.7Weightedleastsquaresfits–outliers..............573 19.8Non-parametricmodels.....................576 19.9Numericalmethod–Gauss-Newton..............580 19.10Application–videodata....................583 19.11Application–breathoftheEarth...............585 19.12Studyquestions.........................587 19.13Exercises.............................588 20Integrals 597 20.1Interpretationofintegrals....................597 20.2Curvelength...........................598 20.3Solidsofrevolution.......................599
©FÖRFATTAREN OCH STUDENTLITTERATUR 12 CONTENTS 20.4IntegralsinPython.......................600 20.5Interpretationofmultipleintegrals...............604 20.6DoubleandtripleintegralsinPython.............605 20.7Numericalmethods.......................608 20.8Application–corrugatedplates................617 20.9Application–diffractionofatelescope............618 20.10Application–gravitationalpull................619 20.11Studyquestions.........................621 20.12Exercises.............................622 21Differentialequations 629 21.1Ordinarydifferentialequations.................629 21.2Systemsofordinarydifferentialequations...........630 21.3Higherorderdifferentialequations...............631 21.4InitialvalueproblemsinPython................632 21.5Initialvalueproblems–stepmethods.............638 21.6Boundaryvalueproblems....................643 21.7Eigenvalueproblems.......................647 21.8Application–populationdynamics..............651 21.9Application–wavefunctionsforhydrogen..........654 21.10Studyquestions.........................656 21.11Exercises.............................658 22MonteCarlomethods 669 22.1Initialexample..........................669 22.2Probabilitydensityfunctions..................670 22.3Randomnumbergeneration..................671 22.4Measureofadomain......................675 22.5Multipleintegrals........................677 22.6Application–Earth’smomentofinertia............679 22.7Application–errorpropagation................681 22.8Application–radiationtransfer................683 22.9Application–idealgasin2D..................686 22.10Studyquestions.........................689 22.11Exercises.............................690 AInstallingAnaconda 695 BJupyterNotebook 697 B.1StartJupyterNotebook.....................697 B.2SaveJupyterNotebook.....................701 B.3Insertingimagesandlinks...................702 B.4Uploaddatafiles.........................702 B.5OpeningaJupyterNotebookfile................703
©FÖRFATTAREN OCH STUDENTLITTERATUR CONTENTS 13 CNumericdatatypes 705 C.1Built-innumericdatatypesinPython.............705 C.2Built-innumericdatatypesinNumPy............706 DSolutionstoselectedexercises 707 22.5Multipleintegrals........................677 22.6Application–Earth’smomentofinertia............679 22.7Application–errorpropagation................681 22.8Application–radiationtransfer................683 22.9Application–idealgasin2D..................686 22.10Studyquestions.........................689 22.11Exercises.............................690 AInstallingAnaconda 695 BJupyterNotebook 697 B.1StartJupyterNotebook.....................697 B.2SaveJupyterNotebook.....................701 B.3Insertingimagesandlinks...................702 B.4Uploaddatafiles.........................702 B.5OpeningaJupyterNotebookfile................703 CONTENTS 13 CNumericdatatypes 705 C.1Built-innumericdatatypesinPython.............705 C.2Built-innumericdatatypesinNumPy............706 DSolutionstoselectedexercises 707 Appendix Index 711
PartI Pythonprogramming
Chapter1 IntroductiontoPython
Pythonisageneralprogramminglanguage,whichwasintroducedin1991 byGuidovanRossum.Thelanguagesupportsobject-orientedprogramming. Pythonisopen-source,meaningthattherearelotsofuserdevelopedpackages.Pythonisusedforscientificcomputing,modelingandsimulation,machinelearning,datamining,computergraphicsandgraphicaluserinterfaces. AsofJune2023Pythonistheworld’smostusedprogramminglanguage.
1.1InstallingPython
WerecommendthatyouinstallAnacondaIndividualEdition,whichisavailableforWindows,Mac,andLinux(seeappendixAforinstallationinstructions).Anacondaincludes,amongotherthings,Python,togetherwithall importantpackages,Spyder,anintegrateddevelopmentenvironment,and JupyterNotebook,abrowserbasedapplicationthatallowsyoutomixexecutablePythoncodewithtext,formulasandmultimedia(seeappendixB togetstartedwiththeNotebook).Anacondaalsomakesiteasytoinstall additionalPythonpackagesusingthebuilt-inpackagemanager,Conda.
1.2Spyderdevelopmentenvironment
Spyderisanintegrateddevelopmentenvironment(IDE)forPythonthat containsacommandwindow,whereyoucanworkinteractively,aneditor, whereyoucanwriteprograms(scripts),andavariableexplorer,whereyou canseewhatvariablesaredefinedandtheirvalues.Spyderalsoincludestools tohandleplotsandtodebugprograms.Spyderisshowninfigure1.1.
Uponstart,Spydergiveswhitetextagainstadarkbackground.Ifyoudon’t likethis,andwanttochangetodarktextagainstawhitebackground,you
©FÖRFATTAREN OCH STUDENTLITTERATUR
Figure1.1: Spyderintegrateddevelopmentenvironment.Thewindowdown totherightisthecommandwindow(IPythonconsole),whereyouenteryour commands.Thewindowtotheleftistheeditor,whereyoucreateyourprogramsorscripts. click,inthetoolbar,on Preferences andchoose Appearance.Under Syntax highlighting, youselect Spyder insteadof SpyderDark.Itispracticaltobe abletointeractivelymanipulateplots.Toenablethis,clickon Preferences andchoose IPythonconsole.Under Graphics,select Backend:Automatic. Inthesubsequenttext,weassumethatthishasbeendone.
1.3Packagesandmodules
WhenstartingPython,thereisonlyalimitednumberofcommands(or functions)available.Mostfunctionsarehiddeninmodules(packages),where wecanthinkofmodulesascontainerswithfunctionsandcommandsfor relatedpurposes.Dependentonthetask,weneedtoimportfunctionsfrom oneormoremodules.Thiscanbedoneindifferentways.Toimportthe function sqrt,whichcomputessquareroots,fromamodulecalled numpy,we givethecommand
©FÖRFATTAREN OCH STUDENTLITTERATUR 18 IntroductiontoPython
fromnumpyimportsqrt
Thefunction sqrt isnowavailable.Tocomputethesquarerootoffourwe write sqrt(4)
Toimportallfunctionsfrom numpy wegivethecommand importnumpy
Whencallingafunctionfromtheimportedmodule,wenowneedtoinclude themodulenameinthefollowingway
numpy.sqrt(4)
Wecanalsoimportthemoduleandgiveitanabbreviatedname.Itis standardtoimport numpy as importnumpyasnp
Thecalltothefunctionisnow
np.sqrt(4)
InordertomasterPython,weneedtoknowwhatmodulesandfunctionsare available.Themostimportantmodules(packages)are math,whichincludes theelementarymathematicalfunctions, numpy,whichallowsustoworkwith multidimensionalarrays, scipy,whichisusedtoperformtasksrelatedto calculusandlinearalgebra,and matplotlib,whichcontainsfunctionsfor plottingandmanipulatinggraphics.Wereturntoallthesemodules(packages)insubsequentchapters.
©FÖRFATTAREN OCH STUDENTLITTERATUR
19
1.4Interactiveruns–Pythonasacalculator
Example1.1. Tocompute 16 27
16*27 andpressreturn.Pythonreturnstheanswer 432 ✷
1.4Interactiveruns–Pythonasacalculator TorunPythoninteractively,wewritethecommandsonthecommandline.
,wewrite
Example1.2. Wewanttocompute sin(π/4).Boththesinefunctionand thevalueof π areavailableinthemodule math,whichshouldbeimported. Thecommandsare
andPythonreturns
0.7071067811865476
Alternatively,wecouldwrite frommathimportsin,pi sin(pi/4)
whichgivesthesameanswer.
Example1.3. Wehavethenumbers1,2,4,2,7,8,2,13andwantto computethemean.Thefunction mean isavailableinthemodule numpy, whichneedstobeimported.Wegivethecommands
1.5Scriptsandpy-files
Aseriesofcommandscollectedinafileiscalledaprogramorascript.The commandsinthefilecanbedividedintosmallerunitscalledcells.Acell startswith #%%.InPython,fileswithcommandsalwayshavetheextension .py andaresometimescalledpy-files.
Programsorscriptsarecreatedintheeditor.Whenyouhavewrittenyour program(script),pressthe Save iconinthetoolbar,andSpyderwillaskyou forthenameofthefile,andinwhichfolderitshouldbesaved.Torun, orexecute,theprogram,whichmeansthatthecommandsareexecutedin order,pressthe Runfile icon(greentriangle).Toexecuteasinglecell,place yourselfinthecellandpressthe Runcell icon(totherightofthe Runfile icon).Theeditor,withcommandsgivenintwocells,isshowninfigure1.2. Namesofpy-filesshouldnotstartwithdigitsorcontainblanks.
©FÖRFATTAREN OCH STUDENTLITTERATUR 20 IntroductiontoPython
importmath math.sin(math.pi/4)
✷
importnumpyasnp x=[1,2,4,2,7,8,2,13] np.mean(x) andPythonreturns 4.875 ✷
Figure1.2: Thewindowtotheleftistheeditor,whereyouwritecommands. Thefirstlineappearsautomatically,andmeansthattheUnicodeTransformationFormat8bits(utf-8)isusedtodecodesymbols.Textwithintriplequotes arecomments.Theprogram,whichhasbeengiventhename funplot.py,is executedorrunbypressingthe Runfile icon.
Toopenanexistingpy-fileclickontheiconfor Open.Youcanalsoentervia File inthemenubar.Whenyouhavedonechangestothefile,thesehaveto besavedbypressingthe Save icon.
Let’staketwoexamples.Textafter # arecommentsandthusignoredby Python.Commentsareimportantforuserstounderstandhowaprogram works.Addingcommentsisanintegralpartofprogramdevelopment.
Example1.4. Wehaveasum s =3+4+5+ ... +52.Thesumiscomputed bythefollowingcommands,whichwewriteintheeditor
#sum.py
s=0
#Setsumstozero foriinrange(3,53):#Loopfrom3andupto52
s=s+i
#Addtermstos.Thislineshould #beindentedfoursteps.
print("Thesumis",s)#Printtheresult.
Note,thatin range theupperboundshouldbetheactualboundplusone, i.e.,53insteadof52.Thecommandsmakeupaprogram,whichissavedto filebyclickingonthe Save iconinthetoolbarandgivingthefileaname.In
©FÖRFATTAREN OCH STUDENTLITTERATUR 1.5Scriptsandpy-files 21
thiscaseweusethename sum.py.Thefile(program)isexecuted,orrun, byclickingonthe Runfile icon,andPythonreturns
Thesumis1375 ✷
Example1.5. Thefollowingcommands,whichwewriteintheeditor,determinethenumberofelementsinavector x andcounthowmanyofthese thatarepositive
#elementcount.py x=[1,2,-1,-2,-3,4,5,6]#Definethevectorx n=len(x)
#Numberofelementsinx npos=0
#Numberofpos.elementssetto0 foriinrange(n):#Loopovertheelementsinx ifx[i]>0: #Ifelementpositive, npos=npos+1#increasenposby1 print("Numberofelements",n)#print print("Numberofpositiveelements",npos)
Thecommandsmakeupaprogram,thatwesavetofileandgivethename elementcount.py.Whenexecutingthefile(program)Pythonwrites
Numberofelements8
Numberofpositiveelements5 ✷
Wewillstudyprogrammingelementslikeif-statementsandfor-loopsinchapters7–10,wheretheimportanceofindentationwillalsobeclarified.
1.6TAB-completion
TAB-completionisextremelyuseful,anditisavailablebothonthecommand lineandintheeditor.WheneveryoustarttowriteaPythonrelatedname, youcanpauseandpresstheTABkeytoseealistofnamesvalidinthis context,thatmatchwiththecharactersalreadytyped.
Example1.6. Wewanttotype importmath.Typing im<andpressTAB>
andpressingTABwillcompletethecommandtogive import
Continuingtotypethecommand
©FÖRFATTAREN OCH STUDENTLITTERATUR 22 IntroductiontoPython
importm<andpressTAB>
andpressingTABreveals30possibilities,ofwhichwecanchoosethedesired importmath.
Example1.7. Wehaveimportedthemodule math through importmath
Toseewhatfunctionsareavailableinthemodule,type math.<andpressTAB>#notetheperiodaftermath andpressTAB.Thisresultsinalistofallfunctionsinthemodule.Thisis bothconvenientandpowerful.
Example1.8. Wearewritingaprogram gravity.py intheeditor
#gravity.py
mass_of_earth=5.972e24
mass_of_moon=7.3476e22
distance=3.844e8
G=6.67408e-11
Tocomputetheforceastheproductofthemassesandthegravitational constantdividedbythedistancesquaredonthenextlineintheprogram, wejustneedtotype mass andpressTABtogetalistofpossiblenamesand choose mass_of_earth.Wethenwrite * and mass andpressTABtoget alistofpossiblenames,andselect mass_of_moon.Thiswillsavealotof typing,andinadditionweavoidspellingerrors.
1.7Goodtoknowcommands
ThereareanumberofIPythonconsolecommandsthataregoodtoknow. Thesearesummarizedbelow.
pwd printsthepresentworkingdirectory(folder).Sameinformation isshowntop-rightintheSpyderIDE,seefigure1.1. ls listsfilesandsubdirectoriesintheworkingdirectory. Canbeusedtogetherwithwildcards*.
whos listsalldefinedvariables.Sameinformationisavailablein Spyder’svariableexplorerwindow,seefigure1.3. reset removesallvariables. clear clearsthecommandwindow.
©FÖRFATTAREN OCH STUDENTLITTERATUR 1.7Goodtoknowcommands 23
✷
✷
✷
Example1.9.
(a)Toclearthecommandwindow,type clear
(b)Toremove(delete)allvariables,wewrite reset
andpressreturn.Ifwenowlistthedefinedvariablesbytyping whos Pythonreturns
Interactivenamespaceisempty.
(c)Wedefinetwovariables a and b a=5 b=[1,2,3,4]
Toseewhatvariablesaredefined,wesimplywrite whos andget
Thesameinformationisavailablefromthevariableexplorerwindow. ✷
1.8Variableexplorer–readandwritetofile
Datatobeusedincomputationsareoftenstoredinfilesindifferentformats. Thesedataneedtobereadandstoredinvariablesforfurtherprocessing andmanipulationinPython.Similarly,dataandvariablesproducedduring aPythonsessiontypicallyneedtobesavedinafilethatcanbesharedwith othersorusedatalaterinstance.Thisissimplifiedbythetoolsbelonging tothevariableexplorerwindow,seefigure1.3.
©FÖRFATTAREN OCH STUDENTLITTERATUR 24 IntroductiontoPython
a
VariableTypeData/Info
int5 b listn=4
Figure1.3: Thevariableexplorerwithinformationaboutthedefinedvariables. Atthetopofthevariableexplorerwindow,therearetoolstoImportdata,Save dataasandRemoveallvariables.
Example1.10. Weremoveallvariablesbygivingthecommand reset#removeallvariables
or,alternatively,byclickingonthe Removeallvariables iconatthetopof thevariableexplorerwindow.Wethendefinethreevariables
m=5 v=12.4
w=[1,2,-1,0]
TosaveallthedefinedvariablesinafileinSpyder’sdatafileformat,we activatethevariableexplorerwindowandpressthe Savedataas iconandgive afilenamealongwithSpyder’sdatafileformatspecification(*.spydata). ForthoseworkingwithMatlab,itisalsopossibletosavevariablesinafile inMatlabformat(*.mat).Wecannowremoveallvariables.
Toreadallthevariablesbackfromthecreatedfile,pressthe Importdata icon.Inthewindowthatcomesupchoose,totheright,Spyder’sdataformat
©FÖRFATTAREN OCH STUDENTLITTERATUR 1.8Variableexplorer–readandwritetofile 25
(*.spydata) andwritethefilename(orclickontheiconwiththedesired file)andclick Open.Wenowhaveaccesstothevariablesanddatainthe importedfile.Ifwetype
whos#listdefinedvariables
Spyderreturns
VariableTypeData/Info
m int5 v float12.4 w listn=4
thatis,wehavetheoriginalvariables.FilesinSpyder’sdatafileformat (*.spydata) areveryconvenientandprovideaneasywaytosaveandexchangedata.
The Importdata iconcanbeusedtoimportdatafromfilesnotonlyin Spyder’sdatafileformat(*.spydata),butfromfilesinanumberofother formats.Theseformatsaregiveninthetablebelow.
Filetype Extension
Spyderdatafiles *.spydata
NumPyarrays *.npy
NumPyziparrays *.npz
Matlabfiles *.mat
CSVtext *.csv
textfiles *.txt
JPEGimages *.jpg
PNGimages *.png
GIFimages *.gif
TIFFimages *.tif
Picklefiles *.pkl
Picklefiles *.pickle
JSONfiles *.json
Wewillreturntoreadingandwritingdatatofileinchapter5.17inrelation toso-calledNumPyarrays.Inchapter6.14wewillreadimagesindifferent fileformats.
1.9LaTeX–documentprograms
WeusePythonforproblem-solving.Aspartofthis,weregularlyneedto documentthedevelopedprograms–howtheyworkandwhatresultsthey
©FÖRFATTAREN OCH STUDENTLITTERATUR 26 IntroductiontoPython
✷
produce.Accordingtotheauthor,thisisbestdoneinLaTeX,afreesoftwaresystemfordocumentpreparation.Inadditiontoefficienthandlingof equationsandformulas,LaTeXallowsyoutodirectlyinsertpy-files.The insertedpy-filesarecolorcoded,whichincreasesreadability.Infigure1.4 weseehowthefile elementcount.py (availableunder”Extramaterial”at studentlitteratur.se/45430)appearswheninsertedinLaTeX.
1 #-*-coding:utf-8-*2 """
3 Countnumberofelementsinavector
4 CreatedonFriJul809:44:462022
16 print ( "Numberofelements" ,n) #print
17 print (
Figure1.4: WheninsertingaPythonfileinLaTeX,thecommandsarecolor coded(notapparenthere,sincethisbookisinblackandwhite).Inaddition, thelinesarenumbered.
YoucaninstallLaTeXonyourlaptop,butitissimplertorunLaTeXvia Overleaf,acollaborativecloudservice.Exercise6helpsyoutogetstarted withLaTeXandOverleaf.Timeinvestedinthisrepays!
1.10Studyquestions
1.Discusssomewaystoimportandusefunctionsfrommodules.
2.Listsomeofthemostimportantmodules(packages).
3.Whatismeantbyaprogram(script)?
4.Commandsareexecutedsequentially.Whatismeantbythis?
5.Whatisapy-file?
6.Howdoyourun(execute)aprogram(py-file)?
7.HowdoesPythoninterprettextfollowing #?
©FÖRFATTAREN OCH STUDENTLITTERATUR 1.10Studyquestions 27
7
9
#Definethevectorx 10 n= len (x) #Numberofelementsinx 11 npos=0 #Numberofpos.elementssetto0 12 for i inrange (n): #Loopovertheelementsinx 13 if x[i]>0: #Ifelementpositive, 14 npos=npos+1 #increasenposby1 15
5 @author:Per 6 """
8 #elementcount.py
x=[1,2,-1,-2,-3,4,-5,6]
"Numberofpositiveelements" ,npos)
8.WhatismeantbyTAB-completion?
9.Whatisavariableexplorer?
10.Explainhowyoucanusethetoolsinthevariableexplorerwindowto savedefinedvariablesinafileinSpyder’sdatafileformat(*.spydata).
11.Howcanyoureadvariablesanddatafromfiles?
1.11Exercises
1.UsePythoninteractivelytocompute 5/113 and cos(π/3)
2.Investigatehowyoucanusethearrowkeys ↑ and ↓ tobrowsebetween commandsenteredonthecommandline.
3.Gototheeditorandenterthecommandsinexample1.8.UseTABcompletiontowritethenewcommand F=G*mass_of_earth*mass_of_moon/distance**2
4.(a)Gototheeditorandenterthecommandsinexample1.4.Makesure thatthecommandsappearexactly,includingindentation,astheyare givenintheexample.Textfollowing # arecommentsandneednotbe entered.Savethefileas sum.py.Runthefileandverifythatyouget thesum1375.
(b)Entertheeditoragainandmakechangessothatthesum s =1+ 2+ +10 iscomputed.Don’tforgettosavethechangesbyclicking onthe Save icon.Runthefileagainandcheckthatthesumturnsout right(itshouldbe55).Pleasenotethattheupperboundinthe range commandshouldbeonemorethanthelargestnumber,i.e.,itshouldbe range(1,11).
5.(a)Gototheeditorandenterthecommandsinexample1.5.Paystrict attentiontotheindentationandmakesurethatitisexactlyasinthe example.Savethefileas elementcount.py.Runthefileandverifythat yougetthecorrectnumberofelements.
(b)Changethepy-filetomakeitcountandreporthowmanyofthe elementsin x thatarenegative.Runthefileagainandcheckthatthe resultiscorrect.
6.Inthefile report.zip (availableunder”Extramaterial”at studentlitteratur.se/45430),youwillfindtheLaTeXfile report.tex alongwiththethreepy-files funplot.py, sum.py and elementcount.py. Inaddition,therearetwoimagefiles, fun1.eps and fun2.eps,created by funplot.py.
©FÖRFATTAREN OCH STUDENTLITTERATUR 28 IntroductiontoPython
(a)CreateanOverleafaccount.
(b)InOverleaf,clickon NewProject andchoose UploadProject.Drag thefile report.zip tothesquarethatappearsinOverleaf.Thefileis automaticallyunzippedandtheLaTeXfileiscompiled.Apdf-fileshould nowappeartotheright.
(c)TesttodosomechangestotheLaTeXfile report.tex,whichisshown totheleftinOverleaf.Press Recompile andwatchhowthepdf-fileto therightchanges.YouhavenowgotstartedwithLaTeXandOverleaf.
7.Definesomevariables.TrytosavethevariablestoafileinSpyder’sdata fileformat(*.spydata).Remove(delete)thedefinedvariablesbygiving thecommand reset.Readbackthevariablesyousavedtofile.Type whos toconfirmthatyougotthevariablesback.
©FÖRFATTAREN OCH STUDENTLITTERATUR 1.11Exercises 29
Per Jönsson is professor in applied mathematics and associate professor in physics at Malmö university. He has extensive teaching experience in programming, mathematics, and scientific computing. He has written several books within these fields and has received the university pedagogical prize.
Programming, Modeling and Simulation in Python
This book focuses on programming, modeling, and simulation in Python, and is directed to a broad group of readers – from beginners who want to learn the basics of programming, to more experienced users who want to use Python for Modeling and Simulation in a wide range of fields.
The first part of the book presents the basics of programming with concrete examples: this is what you write, and this is what you get.
The second part of the book is devoted to the mathematics, mainly linear algebra, and calculus needed for modeling and simulation. The presentation of the mathematics is closely related to the built-in commands and functions in Python.
The third part of the book covers modeling and simulation. Following an overview of the topic, different ways to set up models and run simulations as well as to handle and analyze experimental data are discussed. Again, the presentation is hands on, utilizing the built-in commands and functions in Python.
The book includes numerous exercises with complete solutions, making it suitable for self-studies. At the book’s website (studentlitteratur.se/45430), data files and materials to run all examples are available, as well as complementary materials and solutions to all exercises in the book in terms of executable py-files. In addition, there are py-files for most examples in the book.
Art.nr 45430
studentlitteratur.se