Programming For Computations - Python: A Gentle Introduction To Numerical Simulations With Python 3.6 Svein Linge
Programming For Computations - Python: A Gentle Introduction To Numerical Simulations With Python 3.6 Svein Linge
com
https://textbookfull.com/product/programming-for-
computations-python-a-gentle-introduction-to-
numerical-simulations-with-python-3-6-svein-linge/
https://textbookfull.com/product/introduction-to-scientific-
programming-with-python-joakim-sundnes/
textbookfull.com
https://textbookfull.com/product/python-for-kids-a-playful-
introduction-to-programming-1st-edition-briggs/
textbookfull.com
https://textbookfull.com/product/bite-size-python-an-introduction-to-
python-programming-1st-edition-april-speight/
textbookfull.com
https://textbookfull.com/product/chemistry-the-key-to-our-sustainable-
future-1st-edition-klaudia-czanikova/
textbookfull.com
PV and the NEC 1st Edition Brooks
https://textbookfull.com/product/pv-and-the-nec-1st-edition-brooks/
textbookfull.com
https://textbookfull.com/product/probability-and-statistics-4th-
edition-morris-h-degroot/
textbookfull.com
https://textbookfull.com/product/the-dalek-empire-sourcebook-bbc/
textbookfull.com
https://textbookfull.com/product/anticipation-across-disciplines-1st-
edition-mihai-nadin-eds/
textbookfull.com
https://textbookfull.com/product/recent-advances-in-control-and-
filtering-of-dynamic-systems-with-constrained-signals-ju-h-park/
textbookfull.com
Aging and society Canadian perspectives Eighth Edition
Novak
https://textbookfull.com/product/aging-and-society-canadian-
perspectives-eighth-edition-novak/
textbookfull.com
15
Programming for
Computations –
Python
Second Edition Editorial Board
T. J.Barth
M.Griebel
D.E.Keyes
R.M.Nieminen
D.Roose
T.Schlick
Texts in Computational
Science and Engineering
15
Editors
Timothy J. Barth
Michael Griebel
David E. Keyes
Risto M. Nieminen
Dirk Roose
Tamar Schlick
More information about this series at http://www.springer.com/series/5151
Svein Linge • Hans Petter Langtangen
Programming for
Computations - Python
A Gentle Introduction to Numerical
Simulations with Python 3.6
Second Edition
Svein Linge Hans Petter Langtangen
Fac of Tech, Natural Sci & Maritime Sci Simula Research Laboratory BioComp
University of South-Eastern Norway Lysaker, Norway
Porsgrunn, Norway
Mathematics Subject Classification (2010): 26-01, 34A05, 34A30, 34A34, 39-01, 40-01, 65D15,
65D25, 65D30, 68-01, 68N01, 68N19, 68N30, 70-01, 92D25, 97-04, 97U50
This Springer imprint is published by the registered company Springer Nature Switzerland AG.
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
To My Family
Thanks to my dear wife, Katrin, and our lovely
children, Stian, Mia, and Magnus, for their love,
support, and patience. I am a very lucky man.
To Hans Petter
Dear friend and coauthor, it is so sad you are no
longer among us.1 Thank you for everything. I
dedicate this second edition of our book to you.
vii
viii Preface
3. It is easy to use excellent ready-made software the wrong way. The insight
in programming and the mathematics behind is fundamental for understanding
complex software, avoiding pitfalls, and becoming a safe user.
4. Bugs (errors in computer code) are present in most larger computer programs
(also in the ones from the shop!). What do you do when your ready-made
software gives unexpected results? Is it a bug, is it the wrong use, or is it the
mathematically correct result? Experience with programming of mathematics
gives you a good background for answering these questions. The one who can
program can also make tailored code for a simplified problem setting and use
that to verify the computations done with off-the-shelf software.
5. Lots of skilled people around the world solve computational problems by writing
their own code and offering those for free on the Internet. To take advantage of
this truly great source of software in a reliable way, one must normally be able
to understand and possibly modify computer code offered by others.
6. It is recognized worldwide that students struggle with mathematics and physics.
Too many find such subjects difficult and boring. With programming, we can
execute the good old subjects in a brand new way! According to the authors’
own experience, students find it much more motivating and enlightening when
programming is made an integrated part of mathematics and physical science
courses. In particular, the problem being solved can be much more realistic than
when the mathematics is restricted to what you can do with pen and paper.
7. Finally, we launch our most important argument for learning computer program-
ming: the algorithmic thinking that comes with the process of writing a program
for a computational problem enforces a thorough understanding of both the
problem and the solution method. We can simply quote the famous Norwegian
computer scientist Kristen Nygaard: “Programming is understanding.”
Target Audience and Background Knowledge This book was written for
students, teachers, engineers, and scientists who know nothing about programming
and numerical methods from before but who seek a minimum of the fundamental
skills required to get started with programming as a tool for solving scientific
and engineering problems. Some knowledge of one- and multivariable calculus
is assumed. The basic programming concepts are presented in Chaps. 1–5 (about
150 pages), before practical applications of these concepts are demonstrated in
important mathematical subjects addressed in the remaining parts of the book
(Chaps. 6–9). Each chapter is followed by a set of exercises that covers a wide range
of application areas, e.g., biology, geology, statistics, physics, and mathematics.
The exercises were particularly designed to bring across important points from the
text.
Learning the very basics of programming should not take long, but as with any
other craft, mastering the skill requires continued and extensive practice. Some
beginning practice is gained through Chaps. 6–9, but the authors strongly emphasize
that this is only a start. Students should continue to practice programming in
subsequent courses, while those who exercise self-study should keep up the learning
process through continued application of the craft. The book is a good starting point
when teaching computer programming as an integrated part of standard university
courses in mathematics and natural science. In our experience, such an integration
is doable and indeed rewarding.
Numerical Methods An overall goal with this book is to motivate computer pro-
gramming as a very powerful tool for doing mathematics. All examples are related to
mathematics and its use in engineering and science. However, to solve mathematical
problems through computer programming, we need numerical methods. Explaining
basic numerical methods is therefore an integral part of the book. Our choice of
topics is governed by what is most needed in science and engineering, as well as
in the teaching of applied natural science courses. Mathematical models are then
central, with differential equations constituting the most frequent type of models.
Consequently, the numerical focus in this book is on differential equations. As soft
pedagogical starters for the programming of mathematics, we have chosen the topics
of numerical integration and root finding. We remark that the book is deliberately
brief on numerical methods. This is because our focus is on implementing numerical
algorithms, and to develop reliable, working programs, the programmer must be
confident about the basic ideas of the numerical approximations involved.
How This Book Is Different There are numerous texts on computer programming
and numerical methods, so how does the present one differ from the existing
literature? Compared to standard books on numerical methods, our book has a much
stronger emphasis on the craft of programming and on verification. We want to give
students a thorough understanding of how to think about programming as a problem-
solving method and how to provide convincing evidence for program correctness.
Even though there are lots of books on numerical methods where many algo-
rithms have a corresponding computer implementation (see, e.g., [1, 3–6, 10, 15–
17, 20, 23, 25, 27–31]—the latter two apply Python), it is often assumed that the
reader “can program” beforehand. The present book teaches the craft of structured
programming along with the fundamental ideas of numerical methods. In this book,
unit testing and corresponding test functions are introduced early on. We also put
much emphasis on coding algorithms as functions, as opposed to “flat programs,”
which often dominate in the literature and among practitioners. Functions are
reusable because they utilize the general formulation of a mathematical algorithm
such that it becomes applicable to a large class of problems.
There are also numerous books on computer programming, but not many that
really emphasize how to think about programming in the context of numerical
methods and scientific applications. One such book is [11], which gives a compre-
hensive introduction to Python programming and the thinking about programming
as a computer scientist.
Sometimes, however, one needs a text like the present one. It does not go so
deep into language-specific details, but rather targets the shortest path to reliable
mathematical problem-solving through programming. With this attitude in mind, a
lot of topics were left out of the present book, simply because they were not strictly
needed in the mathematical problem-solving process. Examples of such topics are
object-oriented programming and Python dictionaries (of which the latter omission
is possibly subject to more debate). If you find the present book too shallow, [11]
might be the right choice for you. That source should also work nicely as a more
in-depth successor of the present text.
Whenever the need for a structured introduction to programming arises in science
and engineering courses, the present book may be your option, either for self-study
or for use in organized teaching. The thinking, habits, and practice covered herein
will put readers in a firm position for utilizing and understanding the power of
computers for problem-solving in science and engineering.
1. All code is now in Python version 3.6 (the previous edition was based on Python
version 2.7).
2. In the first edition, the introduction to programming was basically covered in 50
pages by Chap. 1 (The First Few Steps) and Chap. 2 (Basic Constructions). This
is enough to get going, but many readers soon want more details. In this second
edition, these two chapters have therefore been extended and split up into five
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Preface xi
chapters. Explanations are now more complete, previous examples have been
modified, new examples have been added, and more. In particular, the importing
of code is now elaborated on in a greater detail, so is the making of modules.
Also, Sect. 4.2 is new, illustrating the important stepwise strategy of code writing
through a dedicated example. The five first chapters now cover about 150 pages
that explain, in a brief and simple manner, all the code basics required to follow
the remaining parts of the book.
3. The new Chap. 6 (Computing Integrals and Testing Code) and Chap. 7 (Solving
Nonlinear Algebraic Equations) are seen as gentle first applications of program-
ming to problem-solving in mathematics. Both these chapters now precede the
mathematically more challenging Chaps. 8 and 9, which treat basic numerical
solving of ODEs and PDEs, respectively (the chapter Solving Nonlinear Alge-
braic Equations was, in the first edition, the final chapter of the book, but it
seems more appropriate to let it act as a “warm-up” chapter, together with the
new Chap. 6, for the two final chapters on differential equation solving).
4. Section 8.1 (Filling a Water Tank: Two Cases) is new, particularly written for
readers who lack experience with differential equations.
5. Section 8.5 (Rate of Convergence) is new, explaining convergence rate related to
differential equations.
6. New exercises have been added, e.g., on Fibonacci numbers, the Leapfrog
method, Adams-Bashforth methods, and more.
7. Errors and typos have been corrected, and many explanations have been refor-
mulated throughout.
Supplementary Materials All program and data files referred to herein are
available from the book’s (2nd edition) primary web site:
https://github.com/slgit/prog4comp_2.
The authors would also like to thank the Springer team with Dr. Martin Peters,
Thanh-Ha Le Thi, and Leonie Kunz for the effective editorial and production
process.
This text was written in the DocOnce1 [12] markup language.
1 https://github.com/hplgit/doconce.
Abstract
This second edition of the book presents computer programming as a key method
for solving mathematical problems and represents a major revision: all code is now
written in Python version 3.6 (the first edition was based on Python version 2.7).
The first two chapters of the previous edition have been extended and split up into
five new chapters, thus expanding the introduction to programming from 50 to 150
pages. Throughout, explanations are now more complete, previous examples have
been modified, and new sections, examples, and exercises have been added. Also,
errors and typos have been corrected. The book was inspired by the Springer book
TCSE 6, A Primer on Scientific Programming with Python (by Langtangen), but
the style is more accessible and concise in keeping with the needs of engineering
students. The book outlines the shortest possible path from no previous experience
with programming to a set of skills that allows the students to write simple programs
for solving common mathematical problems with numerical methods in engineering
and science courses. The emphasis is on generic algorithms, clean design of
programs, use of functions, and automatic tests for verification.
xiii
Contents
xv
xvi Contents
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
List of Exercises
Exercise 8.12: Use a Backward Euler Scheme for Population Growth . . . . . . . 276
Exercise 8.13: Use a Crank-Nicolson Scheme for Population Growth . . . . . . . 277
Exercise 8.14: Understand Finite Differences via Taylor Series . . . . . . . . . . . . 277
Exercise 8.15: The Leapfrog Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Exercise 8.16: The Runge-Kutta Third Order Method . . . . . . . . . . . . . . . . . . . . 280
Exercise 8.17: The Two-Step Adams-Bashforth Method . . . . . . . . . . . . . . . . . . 280
Exercise 8.18: The Three-Step Adams-Bashforth Method . . . . . . . . . . . . . . . . . 282
Exercise 8.19: Use a Backward Euler Scheme for Oscillations . . . . . . . . . . . . . 282
Exercise 8.20: Use Heun’s Method for the SIR Model . . . . . . . . . . . . . . . . . . . . 283
Exercise 8.21: Use Odespy to Solve a Simple ODE . . . . . . . . . . . . . . . . . . . . . . 283
Exercise 8.22: Set up a Backward Euler Scheme for Oscillations . . . . . . . . . . . 284
Exercise 8.23: Set up a Forward Euler Scheme for Nonlinear and Damped
Oscillations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Exercise 8.24: Solving a Nonlinear ODE with Backward Euler . . . . . . . . . . . . 285
Exercise 8.25: Discretize an Initial Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Exercise 9.1: Simulate a Diffusion Equation by Hand . . . . . . . . . . . . . . . . . . . . 303
Exercise 9.2: Compute Temperature Variations in the Ground . . . . . . . . . . . . . . 303
Exercise 9.3: Compare Implicit Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Exercise 9.4: Explore Adaptive and Implicit Methods . . . . . . . . . . . . . . . . . . . . 305
Exercise 9.5: Investigate the θ Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Exercise 9.6: Compute the Diffusion of a Gaussian Peak . . . . . . . . . . . . . . . . . . 306
Exercise 9.7: Vectorize a Function for Computing the Area of a Polygon . . . . 307
Exercise 9.8: Explore Symmetry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Exercise 9.9: Compute Solutions as t → ∞ . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Exercise 9.10: Solve a Two-Point Boundary Value Problem . . . . . . . . . . . . . . . 309
The First Few Steps
1
Computer Programs Today, most people are experienced with computer pro-
grams, typically programs such as Word, Excel, PowerPoint, Internet Explorer, and
Photoshop. The interaction with such programs is usually quite simple and intuitive:
you click on buttons, pull down menus and select operations, drag visual elements
into locations, and so forth. The possible operations you can do in these programs
can be combined in seemingly an infinite number of ways, only limited by your
creativity and imagination.
Programming The real power of computers can only be utilized if you can
program them, i.e., write the programs yourself. With programming, you can tell
the computer what you want it to do, which is great, since it frees you from possible
limitations that come with programs written by others! Thus, with this skill, you get
an important extra option for problem solving that goes beyond what ready-made
programs offer.
A program that you write, will be a set of instructions that you store in a file.
These instructions must be written (according to certain rules) in a very specialized
language that has adopted words and expressions from English. Such languages
are known as programming (or computer) languages. When you have written your
instructions (your program), you may ask the programming language to read your
program and carry out the instructions. The programming language will then (if
there are no errors) translate the meaning of your instructions into real actions inside
the computer.
To write a program that solves a computing problem, you need to have a thorough
understanding of the given problem. That understanding may have to be developed
along the way and will obviously guide the way you write your solution program.
Typically, you need to write, test and re-write your program several times until you
get it right. Thus, what starts out with a computing problem and ends with a sensible
computer program for its solution, is a process that may take some time. By the term
programming, we will mean the whole of this process.
The purpose of this book is to teach you how to develop computer programs ded-
icated to solve mathematical and engineering problems by fundamental numerical
methods.
do? Well, you may write down the recipe in those three languages and send them
over. Now, if you have been able to think correctly when writing down the recipe,
and you have written the explanations according to the rules in each language, each
of your friends will produce the same cake. Your recipe is the “computer program”,
while English, Russian and Chinese represent the “computer languages” with their
own rules of how to write things. The end product, though, is still the same cake.
Note that you may unintentionally introduce errors in your “recipe”. Depending
on the error, this may cause “baking execution” to stop, or perhaps produce the
wrong cake. In your computer program, the errors you introduce are called bugs
(yes, small insects! . . . for historical reasons), and the process of fixing them is called
debugging. When you try to run your program that contains errors, you usually get
warnings or error messages. However, the response you get depends on the error and
the programming language. You may even get no response, but simply the wrong
“cake”. Note that the rules of a programming language have to be followed very
strictly. This differs from languages like English etc., where the meaning might be
understood even with spelling errors and “slang” included.
We Use Python 3.6 in This Book For good reasons, the programming language
used in this book is Python (version 3.6). It is an excellent language for beginners
(and experts!), with a simple and clear syntax. Some of Python’s other strong
properties are1 : It has a huge and excellent library (i.e., ready-made pieces of
code that you can utilize for certain tasks in your own programs), many global
functions can be placed in only one file, functions are straightforwardly transferred
as arguments to other functions, there is good support for interfacing C, C++ and
Fortran code (i.e., a Python program may use code written in other languages), and
functions explicitly written for scalar input often work fine, without modification,
also with vector input. Another important thing, is that Python is available for free.
It can be downloaded at no cost from the Internet and will run on most platforms.
1 Some of the words here will be new to you, but relax, they will all be explained as we move
along.
Random documents with unrelated
content Scribd suggests to you: