Texts in Computational Science
and Engineering
6
Editors
Timothy J.Barth
Michael Griebel
David E.Keyes
Risto M.Nieminen
Dirk Roose
Tamar Schlick
Hans Petter Langtangen
A Primer on Scientific
Programming with Python
123
2nd Edition
Hans Petter Langtangen
Simula Research Laboratory
Martin Linges vei 17
1325 Lysaker,Fornebu
Norway
hpl@simula.no
ISSN 16110994
ISBN 9783642183652
eISBN 9783642183669
DOI 10.1007/9783642183669
S
p
r
i
n
g
e
r
D
o
r
d
r
e
c
h
t
H
e
i
d
e
l
b
e
r
g
L
o
n
d
o
n
N
e
w
Y
o
r
k
Library of Congress Control Number:
Mathematics Subject Classiﬁcation (2000):
2601,34A05,34A30,34A34,3901,4001,65D15,65D25,
65D30,6801,68N01,68N19,68N
30,7001,92D25,9704,97U50
©SpringerVerlag Berlin Heidelber
This work is subject to copyright.All rights are rese
rved,whether the whole or part of the material is
concerned,speciﬁcally the rights of translation,repr
inting,reuse of illustrations,recitation,broadcasting,
reproduction on microﬁlm or in any other way,and stor
age in data banks.Duplication of this publication
or parts thereof is permitted only
under the provisions of the German Copyright Law of September 9,
1965,in its current version,and permission for use must
always be obtained fromSpr
inger.Violations are
liable to prosecution under the German Copyright Law.
The use of general descriptive names,registered name
s,trademarks,etc.in this publication does not imply,
even in the absence of a speciﬁc statement,that such names are exempt from the relevant protective laws
and regulations and there
fore free for general use.
Cover design:
deblik,Berlin
Printed on acidfree paper
Springer is part of Springer Science+
Business Media (www.springer.com)
On leave from:
Department of Informatics
University of Oslo
P.O.Box 1080 Blindern
0316 Oslo,Norway
http://folk.uio.no/hpl
2011925575
g
2
0
0
9
,
2
0
1
1
Preface
The aimof this book is to teach computer programming using ex
amples
from mathematics and the natural sciences.We have chosen to
use the
Python programming language because it combines remarkabl
e power
with very clean,simple,and compact syntax.Python is easy t
o learn
and very well suited for an introduction to computer program
ming.
Python is also quite similar to Matlab and a good language for
doing
mathematical computing.It is easy to combine Python with co
mpiled
languages,like Fortran,C,and C++,which are widely used la
nguages
for scientiﬁc computations.A seamless integration of Pyth
on with Java
is oﬀered by a special version of Python called Jython.
The examples in this book integrate programming with applic
a
tions to mathematics,physics,biology,and ﬁnance.The rea
der is ex
pected to have knowledge of basic onevariable calculus as t
aught in
mathematicsintensive programs in high schools.It is cert
ainly an ad
vantage to take a university calculus course in parallel,pr
eferably con
taining both classical and numerical aspects of calculus.A
lthough not
strictly required,a background in high school physics make
s many of
the examples more meaningful.
Many introductory programming books are quite compact and f
ocus
on listing functionality of a programming language.Howeve
r,learning
to programis learning how to
think
as a programmer.This book has its
main focus on the thinking process,or equivalently:progra
mming as a
problem solving technique.That is why most of the pages are d
evoted
to case studies in programming,where we deﬁne a problemand e
xplain
how to create the corresponding program.New constructions
and pro
gramming styles (what we could call theory) is also usually i
ntroduced
via examples.Special attention is paid to veriﬁcation of pr
ograms and
to ﬁnding errors.These topics are very demanding for mathem
atical
software,because the unavoidable numerical approximatio
n errors are
possibly mixed with programming mistakes.
v
vi
Preface
By studying the many examples in the book,I hope readers will
learn how to think right and thereby write programs in a quick
er and
more reliable way.Remember,nobody can learn programming b
y just
reading – one has to solve a large amount of exercises hands on
.The
book is therefore full of exercises of various types:modiﬁc
ations of
existing examples,completely new problems,or debugging o
f given
programs.
To work with this book,I recommend to use Python version 2.7
(although version 2.6 will work for most of the material).Fo
r Chap
ters 5–9 and Appendices A–E you also need the NumPy,Matplotl
ib,
SciTools packages.There is a web page associated with this b
ook,
http://www.simula.no/introprogramming
,which lists the software you
need and explains brieﬂy how to install it.On this page,you w
ill also
ﬁnd all the ﬁles associated with the program examples in this
book.
Download
bookexamples.tar.gz
,store this ﬁle in some folder of your
choice,and unpack it using WinZip on Windows or the command
tar
xzf bookexamples.tar.gz
on Linux and Mac.This unpacking yields a
folder
src
with subfolders for the various chapters in the book.
Python version 2 or 3?
A common problem among Python program
mers is to choose between version 2 or 3,which at the time of th
is writ
ing means choosing between version 2.7 and 3.1.The general r
ecom
mendation is to go for version 3,but programs are then not com
patible
with version 2 and vice versa.There is still a problemthat mu
ch useful
mathematical software in Python has not yet been ported to ve
rsion
3.Therefore,scientiﬁc computing with Python still goes mo
stly with
version 2.A widely used strategy for software developers wh
o want
to write Python code that works with both versions,is to deve
lop for
v2.7,which is very close to v3.1,and then use the ranslation
tool
2to3
to automatically translate the code to version 3.1.
When using v2.7,one should employ the newest syntax and mod
ules that make the diﬀerences beween version 2 and 3 very smal
l.This
strategy is adopted in the present book.Only two diﬀerences
between
version 2 and 3 are expected to be signiﬁcant for the programs
in
the book:
a/b
implies ﬂoat division in version 3 if
a
and
b
are inte
gers,and
print ’Hello’
in version 2 must be turned into a function
call
print(’Hello’)
in version 3.None of these diﬀerences should lead
to any annoying problems when future readers study the book’
s v2.7
examples,but program in version 3.Anyway,running 2to3 on t
he ex
ample ﬁles generates the corresponding version 3 code.
Contents.
Chapter 1 introduces variables,objects,modules,and text
formatting through examples concerning evaluation of math
ematical
formulas.Chapter 2 presents programming with
while
and
for
loops
as well as with lists,including nested lists.The next chapt
er deals
with two other fundamental concepts in programming:functi
ons and
Preface
vii
if

else
tests.Successful further reading of the book demands that
Chapters 1–3 are digested.
How to read data into programs and deal with errors in input ar
e the
subjects of Chapter 4.Chapter 5 introduces arrays and array
comput
ing (including vectorization) and how this is used for plott
ing
y
=
f
(
x
)
curves and making animation of curves.Many of the examples i
n the
ﬁrst ﬁve chapters are strongly related.Typically,formula
s fromthe ﬁrst
chapter are used to produce tables of numbers in the second ch
apter.
Then the formulas are encapsulated in functions in the third
chapter.
In the next chapter,the input to the functions are fetched fr
om the
command line,or from a questionanswer dialog with the user
,and
validity checks of the input are added.The formulas are then
shown
as graphs in Chapter 5.After having studied Chapters 1 5,th
e reader
should have enough knowledge of programming to solve mathem
atical
problems by “Matlabstyle” programming.
Chapter 6 explains how to work with ﬁles and text data.Class
programming,including userdeﬁned types for mathematica
l compu
tations (with overloaded operators),is introduced in Chap
ter 7.Chap
ter 8 deals with randomnumbers and statistical computing wi
th appli
cations to games and random walks.Objectoriented program
ming,in
the meaning of class hierarchies and inheritance,is the sub
ject of Chap
ter 9.The key examples here deal with building toolkits for n
umerical
diﬀerentiation and integration as well as graphics.
Appendix Aintroduces mathematical modeling,using sequen
ces and
diﬀerence equations.We also treat sound as a sequence.Only
program
ming concepts from Chapters 1–5 are used in this appendix,th
e aim
being to consolidate basic programming knowledge and apply
it to
mathematical problems.Some important mathematical topic
s are in
troduced via diﬀerence equations in a simple way:Newton’s m
ethod,
Taylor series,inverse functions,and dynamical systems.
Appendix B deals with functions on a mesh,numerical diﬀeren
ti
ation,and numerical integration.A simple introduction to
ordinary
diﬀerential equations and their numerical treatment is pro
vided in Ap
pendix C.Appendix D shows how a complete project in physics c
an be
solved by mathematical modeling,numerical methods,and pr
ogram
ming elements from Chapters 1–5.This project is a good examp
le on
problem solving in computational science,where it is neces
sary to in
tegrate physics,mathematics,numerics,and computer scie
nce.
How to create software for solving systems of ordinary diﬀer
ential
equations,primarily using classes and objectoriented pr
ogramming,
is the subject of Appendix E.The material in this appendix br
ings
together many of the programming concepts from Chapters 1–9
in a
mathematical setting and ends up with a ﬂexible and general t
ool for
solving diﬀerential equations.
viii
Preface
Appendix F is devoted to the art of debugging,and in fact prob
lem
solving in general,while Appendix Gdeals with various more
advanced
technical topics.
Most of the examples and exercises in this book are quite com
pact and limited.However,many of the exercises are related
,and to
gether they form larger projects in science,for example on F
ourier
Series (3.7,4.18–4.20,5.29,5.30),Taylor series (3.21,5
.20,5.27,A.16,
A.17,7.23),falling objects (E.5,E.6,E.7,E.25,E.26),os
cillatory popu
lation growth (A.21,A.22,6.25,7.34,7.35),analysis of we
b data (6.22,
6.28–6.30),graphics and animation (9.20–9.23),optimiza
tion and ﬁ
nance (A.23,8.42,8.43),statistics and probability (4.24
–4.26,8.22–
8.24),hazard games (8.8–8.13),random walk and statistica
l physics
(8.33–8.40),noisy data analysis (8.44–8.48),numerical m
ethods (5.13,
5.14,7.9,A.12,7.22,9.16–9.18,E.15–E.23),building a ca
lculus cal
culator (7.36,7.37,9.24,9.25),and creating a toolkit for
simulating
vibrating engineering systems (E.30–E.37).
Chapters 1–9 and Appendix E have,from2007,formed the core o
f an
introductory ﬁrstsemester course on scientiﬁc programmi
ng,INF1100,
at the University of Oslo (see below).
Changes to the First Edition.
Besides numerous corrections of mis
prints,the second edition features a major reorganization
of several
chapters.Chapter 2 in the ﬁrst edition,
Basic Constructions
,was a
comprehensive chapter,both with respect to length and topi
cs.This
chapter has therefore been split in two for the second editio
n:a new
Chapter 2
Loops and Lists
and a new Chapter 3
Functions and Branch
ing
.A new Chapter 2.1.4 explicitly explains how to implement a s
um
mation expression by a loop,and later examples present alte
rnative
implementations.
All text and program ﬁles that used the
getopt
module to parse
commandline options in the ﬁrst edition now make use of the s
impler
and more ﬂexible
argparse
module (new in Python v2.7/3.1).
The material on curve plotting in Chapter 5 has been thorough
ly
revised.Nowwe give an introduction to plotting with Matplo
tlib as well
as SciTools/Easyviz.Both tools are very similar from a synt
ax point
of view.Much of the more detailed information on Easyviz plo
tting in
the ﬁrst edition has been removed,and the reader is directed
to the
online manuals for more details.
While the ﬁrst edition almost exclusively used“star import
”for con
venience (e.g.,
from numpy import *
and
from scitools.std import *
),
the second edition tries to adhere to the standard
import numpy as
np
.However,in mathematical formulas that are to work with sca
lar
and
array variables,we do not want an explicit preﬁx.Avoiding t
he
namespace preﬁxes is important for making formulas as close
to the
mathematical notation as possible as well as for making the t
ransition
Preface
ix
from or to Matlab smooth.The two import styles have diﬀerent
merits
and applications.The choice of style in various examples is
carefully
thought through in the second edition.
Chapter 5 in the ﬁrst edition,
Sequences and Diﬀerence Equations
,
has now become Appendix A since the material is primarily abo
ut
mathematical modeling,and no new basic programming concep
ts are
introduced.
Chapter 6 in the ﬁrst edition,
Files,Strings,and Dictionaries
,has
been substantially revised.Now,Chapter 6.4,on downloadi
ng and in
terpreting data from web pages,have completely new example
s.Many
of the exercises in this chapter are also reworked to ﬁt with t
he new
examples.
The material on diﬀerential equations in chapters on classe
s (Ch.7
and 9 in the ﬁrst edition) has been extracted,reworked,slig
htly ex
panded,and placed in Appendix E.This restructuring allows
a more
ﬂexible treatment of diﬀerential equations,and parts of th
is impor
tant topic can be addressed right after Chapter 3,if desired
.Also,the
changes make readers of Chapters 7 and 9 less disturbed with m
ore
diﬃcult mathematical subjects.
To distinguish between Python’s
random
module and the one in
numpy
,we have in Chapter 8 changed practice compared with the ﬁrst
edition.Now
random
always refers to Python’s
random
module,while
the
random
module in
numpy
is normally invoked as
np.random
(or oc
casionally as
numpy.random
).The associated software has been revised
similarly.
Acknowledgments.
First,I want to express my thanks to Aslak Tveito
for his enthusiastic role in the initiation of this book proj
ect and for
writing Appendices B and C about numerical methods.Without
Aslak
there would be no book.Another key contributor is Ilmar Wilb
ers.His
extensive eﬀorts with assisting the book project and help es
tablishing
the associated course (INF1100) at the University of Oslo ar
e greatly
appreciated.Without Ilmar and his solutions to numerous te
chnical
problems the book would never have been completed.Johannes
H.Ring
also deserves a special acknowledgment for the development
of the
Easyviz graphics tool,which is much used throughout this bo
ok,and
for his careful maintenance and support of software associa
ted with
this book.
Several people have helped to make substantial improvement
s of
the text,the exercises,and the associated software infras
tructure.
The author is thankful to Ingrid Eide,Arve Knudsen,Tobias V
i
darssønn Langhoﬀ,Solveig Masvie,H˚akon Møller,Mathias Ne
drebø,
Marit Sandstad,Lars Storjord,Fredrik Heﬀer Valdmanis,and
Torkil
Vederhus for their contributions.Hakon Adler is greatly ac
knowledged
for his careful reading of various versions of the manuscrip
t.The pro
x
Preface
fessors Fred Espen Bent,Ørnulf Borgan,Geir Dahl,Knut Mørk
en,and
Geir Pedersen have contributed with many exciting exercise
s from var
ious application ﬁelds.Great thanks also go to Jan Olav Langs
eth for
creating the cover image.
This book and the associated course are parts of a comprehens
ive
reform at the University of Oslo,called
Computers in Science Edu
cation
.The goal of the reform is to integrate computer programming
and simulation in all bachelor courses in natural science wh
ere mathe
matical models are used.The present book lays the foundatio
n for the
modern computerized problem solving technique to be applie
d in later
courses.It has been extremely inspiring to work with the dri
ving forces
behind this reform,in particular the professors Morten Hjo
rth–Jensen,
Anders Malthe–Sørenssen,Knut Mørken,and Arnt Inge Vistne
s.
The excellent assistance fromthe Springer and letex teams
,consist
ing of Martin Peters,ThanhHa Le Thi,Ruth Allewelt,Peggy Gl
auch
Ruge,Nadja Kroke,Thomas Schmidt,and Patrick Waltemate,i
s highly
appreciated,and ensured a smooth and rapid production of bo
th the
ﬁrst and the second edition of this book.
Oslo,February 2011 Hans Petter Langtangen
Contents
1 Computing with Formulas
.........................
1
1.1 The First Programming Encounter:A Formula.......1
1.1.1 Using a Program as a Calculator.............2
1.1.2 About Programs and Programming...........2
1.1.3 Tools for Writing Programs..................3
1.1.4 Using Idle to Write the Program..............4
1.1.5 How to Run the Program....................7
1.1.6 Verifying the Result.........................8
1.1.7 Using Variables.............................8
1.1.8 Names of Variables..........................9
1.1.9 Reserved Words in Python...................10
1.1.10 Comments.................................10
1.1.11 Formatting Text and Numbers...............11
1.2 Computer Science Glossary.........................
14
1.3 Another Formula:CelsiusFahrenheit Conversion.....
.19
1.3.1 Potential Error:Integer Division..............19
1.3.2 Objects in Python..........................20
1.3.3 Avoiding Integer Division....................21
1.3.4 Arithmetic Operators and Precedence.........22
1.4 Evaluating Standard Mathematical Functions.........
22
1.4.1 Example:Using the Square Root Function.....23
1.4.2 Example:Using More Mathematical Functions.25
1.4.3 A First Glimpse of RoundOﬀ Errors..........25
1.5 Interactive Computing............................
.26
1.5.1 Calculating with Formulas in the Interactive
Shell......................................27
1.5.2 Type Conversion............................28
1.5.3 IPython...................................29
1.6 Complex Numbers................................31
xi
xii
Contents
1.6.1 Complex Arithmetics in Python..............32
1.6.2 Complex Functions in Python................33
1.6.3 Uniﬁed Treatment of Complex and Real
Functions..................................33
1.7 Summary........................................3
5
1.7.1 Chapter Topics.............................35
1.7.2 Summarizing Example:Trajectory of a Ball....38
1.7.3 About Typesetting Conventions in This Book..40
1.8 Exercises.......................................
..41
2 Loops and Lists
....................................
51
2.1 While Loops......................................5
1
2.1.1 A Naive Solution...........................51
2.1.2 While Loops...............................52
2.1.3 Boolean Expressions........................54
2.1.4 Loop Implementation of a Sum...............56
2.2 Lists............................................
.57
2.2.1 Basic List Operations.......................58
2.2.2 For Loops..................................60
2.3 Alternative Implementations with Lists and Loops....62
2.3.1 While Loop Implementation of a For Loop.....62
2.3.2 The Range Construction.....................62
2.3.3 For Loops with List Indices..................63
2.3.4 Changing List Elements.....................65
2.3.5 List Comprehension.........................65
2.3.6 Traversing Multiple Lists Simultaneously......66
2.4 Nested Lists......................................
66
2.4.1 A Table as a List of Rows or Columns.........67
2.4.2 Printing Objects............................68
2.4.3 Extracting Sublists..........................69
2.4.4 Traversing Nested Lists......................71
2.5 Tuples..........................................
.73
2.6 Summary........................................7
4
2.6.1 Chapter Topics.............................74
2.6.2 Summarizing Example:Analyzing List Data...77
2.6.3 How to Find More Python Information........80
2.7 Exercises.......................................
..81
3 Functions and Branching
..........................
91
3.1 Functions.......................................
.91
3.1.1 Functions of One Variable...................91
3.1.2 Local and Global Variables...................93
3.1.3 Multiple Arguments.........................95
3.1.4 Multiple Return Values......................97
3.1.5 Functions with No Return Values.............99
Contents
xiii
3.1.6 Keyword Arguments........................100
3.1.7 Doc Strings................................103
3.1.8 Function Input and Output..................104
3.1.9 Functions as Arguments to Functions.........104
3.1.10 The Main Program.........................106
3.1.11 Lambda Functions..........................107
3.2 Branching.......................................
.108
3.2.1 IfElse Blocks..............................108
3.2.2 Inline If Tests..............................110
3.3 Summary........................................1
11
3.3.1 Chapter Topics.............................111
3.3.2 Summarizing Example:Numerical Integration..113
3.4 Exercises.......................................
..116
4 Input Data and Error Handling
...................
129
4.1 Asking Questions and Reading Answers..............13
0
4.1.1 Reading Keyboard Input....................130
4.1.2 The Magic “eval” Function...................131
4.1.3 The Magic “exec” Function...................135
4.1.4 Turning String Expressions into Functions.....136
4.2 Reading from the Command Line...................137
4.2.1 Providing Input on the Command Line........137
4.2.2 A Variable Number of CommandLine
Arguments.................................138
4.2.3 More on CommandLine Arguments...........139
4.2.4 Option–Value Pairs on the Command Line.....140
4.3 Handling Errors..................................
.142
4.3.1 Exception Handling.........................143
4.3.2 Raising Exceptions..........................146
4.4 A Glimpse of Graphical User Interfaces..............1
48
4.5 Making Modules..................................1
51
4.5.1 Example:Compund Interest Formulas.........152
4.5.2 Collecting Functions in a Module File.........153
4.5.3 Using Modules.............................157
4.6 Summary........................................1
59
4.6.1 Chapter Topics.............................159
4.6.2 Summarizing Example:Bisection Root Finding.162
4.7 Exercises.......................................
..170
5 Array Computing and Curve Plotting
............
177
5.1 Vectors.........................................
.178
5.1.1 The Vector Concept.........................178
5.1.2 Mathematical Operations on Vectors..........179
5.1.3 Vector Arithmetics and Vector Functions......181
5.2 Arrays in Python Programs........................18
3
xiv
Contents
5.2.1 Using Lists for Collecting Function Data.......183
5.2.2 Basics of Numerical Python Arrays...........184
5.2.3 Computing Coordinates and Function Values...185
5.2.4 Vectorization...............................18
6
5.3 Curve Plotting...................................
.188
5.3.1 Matplotlib;Pylab...........................188
5.3.2 Matplotlib;Pyplot..........................192
5.3.3 SciTools and Easyviz........................194
5.3.4 Making Animations.........................199
5.3.5 Curves in Pure Text........................203
5.4 Plotting Diﬃculties..............................
..204
5.4.1 Piecewisely Deﬁned Functions................205
5.4.2 Rapidly Varying Functions...................210
5.4.3 Vectorizing StringFunction Objects...........211
5.5 More on Numerical Python Arrays..................212
5.5.1 Copying Arrays.............................212
5.5.2 InPlace Arithmetics........................213
5.5.3 Allocating Arrays...........................214
5.5.4 Generalized Indexing........................214
5.5.5 Testing for the Array Type..................215
5.5.6 Compact Syntax for Array Generation.........216
5.5.7 Shape Manipulation.........................216
5.6 HigherDimensional Arrays........................
.217
5.6.1 Matrices and Arrays........................217
5.6.2 TwoDimensional Numerical Python Arrays....218
5.6.3 Array Computing...........................220
5.6.4 TwoDimensional Arrays and Functions of Two
Variables..................................221
5.6.5 Matrix Objects.............................222
5.7 Summary........................................2
23
5.7.1 Chapter Topics.............................223
5.7.2 Summarizing Example:Animating a Function..224
5.8 Exercises.......................................
..229
6 Files,Strings,and Dictionaries
....................
243
6.1 Reading Data from File............................2
43
6.1.1 Reading a File Line by Line..................244
6.1.2 Reading a Mixture of Text and Numbers......247
6.1.3 What Is a File,Really?......................248
6.2 Dictionaries....................................
..252
6.2.1 Making Dictionaries.........................252
6.2.2 Dictionary Operations.......................253
6.2.3 Example:Polynomials as Dictionaries.........254
6.2.4 Example:File Data in Dictionaries............256
6.2.5 Example:File Data in Nested Dictionaries.....257
Contents
xv
6.2.6 Example:Comparing Stock Prices............262
6.3 Strings.........................................
..266
6.3.1 Common Operations on Strings...............266
6.3.2 Example:Reading Pairs of Numbers..........270
6.3.3 Example:Reading Coordinates...............272
6.4 Reading Data from Web Pages......................274
6.4.1 About Web Pages...........................274
6.4.2 How to Access Web Pages in Programs........276
6.4.3 Example:Reading Pure Text Files............277
6.4.4 Example:Extracting Data from an HTML Page 278
6.5 Writing Data to File...............................
279
6.5.1 Example:Writing a Table to File.............280
6.5.2 Standard Input and Output as File Objects....281
6.5.3 Reading and Writing Spreadsheet Files........284
6.6 Summary........................................2
89
6.6.1 Chapter Topics.............................289
6.6.2 Summarizing Example:A File Database.......291
6.7 Exercises.......................................
..294
7 Introduction to Classes
............................
305
7.1 Simple Function Classes...........................
.306
7.1.1 Problem:Functions with Parameters..........306
7.1.2 Representing a Function as a Class............308
7.1.3 Another Function Class Example.............314
7.1.4 Alternative Function Class Implementations....315
7.1.5 Making Classes Without the Class Construct...317
7.2 More Examples on Classes.........................32
0
7.2.1 Bank Accounts.............................320
7.2.2 Phone Book................................322
7.2.3 A Circle...................................323
7.3 Special Methods..................................
324
7.3.1 The Call Special Method....................325
7.3.2 Example:Automagic Diﬀerentiation...........325
7.3.3 Example:Automagic Integration..............328
7.3.4 Turning an Instance into a String.............330
7.3.5 Example:Phone Book with Special Methods...331
7.3.6 Adding Objects.............................333
7.3.7 Example:Class for Polynomials...............333
7.3.8 Arithmetic Operations and Other Special
Methods...................................337
7.3.9 Special Methods for String Conversion.........338
7.4 Example:Class for Vectors in the Plane..............3
40
7.4.1 Some Mathematical Operations on Vectors.....340
7.4.2 Implementation.............................340
7.4.3 Usage.....................................342
xvi
Contents
7.5 Example:Class for Complex Numbers...............343
7.5.1 Implementation.............................344
7.5.2 Illegal Operations...........................34
5
7.5.3 Mixing Complex and Real Numbers...........346
7.5.4 Special Methods for “Right” Operands.........348
7.5.5 Inspecting Instances.........................35
0
7.6 Static Methods and Attributes......................
351
7.7 Summary........................................3
52
7.7.1 Chapter Topics.............................352
7.7.2 Summarizing Example:Interval Arithmetics....353
7.8 Exercises.......................................
..359
8 Random Numbers and Simple Games
............
375
8.1 Drawing Random Numbers.........................376
8.1.1 The Seed..................................376
8.1.2 Uniformly Distributed Random Numbers......377
8.1.3 Visualizing the Distribution..................37
8
8.1.4 Vectorized Drawing of Random Numbers......379
8.1.5 Computing the Mean and Standard Deviation..380
8.1.6 The Gaussian or Normal Distribution.........381
8.2 Drawing Integers.................................
.382
8.2.1 Random Integer Functions...................383
8.2.2 Example:Throwing a Die....................384
8.2.3 Drawing a Random Element from a List.......385
8.2.4 Example:Drawing Cards from a Deck.........385
8.2.5 Example:Class Implementation of a Deck.....387
8.3 Computing Probabilities..........................
.390
8.3.1 Principles of Monte Carlo Simulation..........390
8.3.2 Example:Throwing Dice.....................391
8.3.3 Example:Drawing Balls from a Hat...........393
8.3.4 Example:Policies for Limiting Population
Growth....................................395
8.4 Simple Games....................................3
98
8.4.1 Guessing a Number.........................398
8.4.2 Rolling Two Dice...........................398
8.5 Monte Carlo Integration...........................
401
8.5.1 Standard Monte Carlo Integration............401
8.5.2 Area Computing by Throwing Random Points..404
8.6 Random Walk in One Space Dimension..............406
8.6.1 Basic Implementation.......................406
8.6.2 Visualization...............................40
7
8.6.3 Random Walk as a Diﬀerence Equation........408
8.6.4 Computing Statistics of the Particle Positions..408
8.6.5 Vectorized Implementation...................409
8.7 Random Walk in Two Space Dimensions.............411
Contents
xvii
8.7.1 Basic Implementation.......................411
8.7.2 Vectorized Implementation...................413
8.8 Summary........................................4
14
8.8.1 Chapter Topics.............................414
8.8.2 Summarizing Example:Random Growth.......415
8.9 Exercises.......................................
..421
9 ObjectOriented Programming
....................
437
9.1 Inheritance and Class Hierarchies..................
.437
9.1.1 A Class for Straight Lines....................438
9.1.2 A First Try on a Class for Parabolas..........439
9.1.3 A Class for Parabolas Using Inheritance.......439
9.1.4 Checking the Class Type....................441
9.1.5 Attribute versus Inheritance..................44
2
9.1.6 Extending versus Restricting Functionality.....44
3
9.1.7 Superclass for Deﬁning an Interface...........444
9.2 Class Hierarchy for Numerical Diﬀerentiation........
.446
9.2.1 Classes for Diﬀerentiation....................44
7
9.2.2 A Flexible Main Program....................450
9.2.3 Extensions.................................451
9.2.4 Alternative Implementation via Functions......454
9.2.5 Alternative Implementation via Functional
Programming..............................455
9.2.6 Alternative Implementation via a Single Class..456
9.3 Class Hierarchy for Numerical Integration...........
.458
9.3.1 Numerical Integration Methods...............458
9.3.2 Classes for Integration.......................45
9
9.3.3 Using the Class Hierarchy....................463
9.3.4 About ObjectOriented Programming.........466
9.4 Class Hierarchy for Geometric Shapes...............4
67
9.4.1 Using the Class Hierarchy....................467
9.4.2 Overall Design of the Class Hierarchy.........469
9.4.3 The Drawing Tool..........................470
9.4.4 Implementation of Shape Classes.............472
9.4.5 Scaling,Translating,and Rotating a Figure....476
9.5 Summary........................................4
80
9.5.1 Chapter Topics.............................480
9.5.2 Summarizing Example:Input Data Reader.....482
9.6 Exercises.......................................
..488
A Sequences and Diﬀerence Equations
..............
497
A.1 Mathematical Models Based on Diﬀerence Equations..498
A.1.1 Interest Rates..............................499
A.1.2 The Factorial as a Diﬀerence Equation........501
A.1.3 Fibonacci Numbers.........................502
xviii
Contents
A.1.4 Growth of a Population......................503
A.1.5 Logistic Growth............................504
A.1.6 Payback of a Loan..........................506
A.1.7 Taylor Series as a Diﬀerence Equation.........507
A.1.8 Making a Living from a Fortune..............508
A.1.9 Newton’s Method...........................509
A.1.10 The Inverse of a Function....................513
A.2 Programming with Sound..........................51
5
A.2.1 Writing Sound to File.......................515
A.2.2 Reading Sound from File....................516
A.2.3 Playing Many Notes........................517
A.2.4 Music of a Sequence.........................518
A.3 Exercises.......................................
..521
B Introduction to Discrete Calculus
.................
529
B.1 Discrete Functions...............................
.529
B.1.1 The Sine Function..........................530
B.1.2 Interpolation...............................53
2
B.1.3 Evaluating the Approximation................532
B.1.4 Generalization..............................53
3
B.2 Diﬀerentiation Becomes Finite Diﬀerences...........
.535
B.2.1 Diﬀerentiating the Sine Function..............536
B.2.2 Diﬀerences on a Mesh.......................536
B.2.3 Generalization..............................53
8
B.3 Integration Becomes Summation....................5
39
B.3.1 Dividing into Subintervals...................540
B.3.2 Integration on Subintervals..................541
B.3.3 Adding the Subintervals.....................542
B.3.4 Generalization..............................54
3
B.4 Taylor Series....................................
.545
B.4.1 Approximating Functions Close to One Point...545
B.4.2 Approximating the Exponential Function......545
B.4.3 More Accurate Expansions...................546
B.4.4 Accuracy of the Approximation...............548
B.4.5 Derivatives Revisited........................55
0
B.4.6 More Accurate Diﬀerence Approximations.....551
B.4.7 SecondOrder Derivatives....................553
B.5 Exercises.......................................
..555
C Introduction to Diﬀerential Equations
............
561
C.1 The Simplest Case................................5
62
C.2 Exponential Growth...............................
564
C.3 Logistic Growth...................................
569
C.4 A Simple Pendulum...............................57
0
C.5 A Model for the Spread of a Disease.................573
Contents
xix
C.6 Exercises.......................................
..575
D A Complete Diﬀerential Equation Project
........
577
D.1 About the Problem:Motion and Forces in Physics.....577
D.1.1 The Physical Problem.......................577
D.1.2 The Computational Algorithm...............580
D.1.3 Derivation of the Mathematical Model.........580
D.1.4 Derivation of the Algorithm..................583
D.2 Program Development and Testing..................58
4
D.2.1 Implementation.............................584
D.2.2 Callback Functionality.......................58
7
D.2.3 Making a Module...........................588
D.2.4 Veriﬁcation................................589
D.3 Visualization...................................
..591
D.3.1 Simultaneous Computation and Plotting.......591
D.3.2 Some Applications..........................594
D.3.3 Remark on Choosing
t
.....................594
D.3.4 Comparing Several Quantities in Subplots.....595
D.3.5 Comparing Approximate and Exact Solutions..596
D.3.6 Evolution of the Error as
t
Decreases........597
D.4 Exercises.......................................
..601
E Programming of Diﬀerential Equations
...........
603
E.1 Scalar Ordinary Diﬀerential Equations..............
.604
E.1.1 Examples on RightHandSide Functions.......604
E.1.2 The Forward Euler Scheme..................606
E.1.3 Function Implementation....................607
E.1.4 Verifying the Implementation.................607
E.1.5 Switching Numerical Method.................608
E.1.6 Class Implementation.......................609
E.1.7 Example:Logistic Growth...................612
E.2 Systems of Ordinary Diﬀerential Equations...........
613
E.2.1 Mathematical Problem......................614
E.2.2 Example of a System of ODEs................615
E.2.3 From Scalar ODE Code to Systems...........616
E.2.4 Numerical Methods.........................619
E.2.5 The ODE Solver Class Hierarchy.............621
E.2.6 The Backward Euler Method.................623
E.2.7 Application 1:
u
′
=
u
........................626
E.2.8 Application 2:The Logistic Equation..........627
E.2.9 Application 3:An Oscillating System..........629
E.2.10 Application 4:The Trajectory of a Ball........631
E.3 Exercises.......................................
..633
F Debugging
.........................................
655
F.1 Using a Debugger.................................6
55
xx
Contents
F.2 How to Debug....................................65
8
F.2.1 A Recipe for Program Writing and Debugging..658
F.2.2 Application of the Recipe....................660
G Technical Topics
...................................
673
G.1 Diﬀerent Ways of Running Python Programs.........673
G.1.1 Executing Python Programs in IPython.......673
G.1.2 Executing Python Programs on Unix..........673
G.1.3 Executing Python Programs on Windows......675
G.1.4 Executing Python Programs on Macintosh.....677
G.1.5 Making a Complete StandAlone Executable...677
G.2 Integer and Float Division.........................
.677
G.3 Visualizing a Program with Lumpy..................678
G.4 Doing Operating System Tasks in Python............681
G.5 Variable Number of Function Arguments.............68
3
G.5.1 Variable Number of Positional Arguments.....683
G.5.2 Variable Number of Keyword Arguments......686
G.6 Evaluating Program Eﬃciency......................6
88
G.6.1 Making Time Measurements.................688
G.6.2 Proﬁling Python Programs...................690
Bibliography
...........................................
693
Index
..................................................
695
List of Exercises
Exercise 1.1 Compute 1+1..............................
.43
Exercise 1.2 Write a “Hello,World!” program.............
..43
Exercise 1.3 Derive and compute a formula................
.43
Exercise 1.4 Convert from meters to British length units...
..43
Exercise 1.5 Compute the mass of various substances.......
.43
Exercise 1.6 Compute the growth of money in a bank........43
Exercise 1.7 Find error(s) in a program..................
..44
Exercise 1.8 Type in program text.......................
.44
Exercise 1.9 Type in programs and debug them.............4
4
Exercise 1.10 Evaluate a Gaussian function..............
....45
Exercise 1.11 Compute the air resistance on a football.....
...45
Exercise 1.12 Deﬁne objects in IPython..................
...46
Exercise 1.13 How to cook the perfect egg.................
..46
Exercise 1.14 Derive the trajectory of a ball.............
....47
Exercise 1.15 Find errors in the coding of formulas........
...48
Exercise 1.16 Explain why a program does not work..........
48
Exercise 1.17 Find errors in Python statements...........
...48
Exercise 1.18 Find errors in the coding of a formula........
..49
Exercise 2.1 Make a Fahrenheit–Celsius conversion table..
...81
Exercise 2.2 Write an approximate Fahrenheit–Celsius
conversion table.............................81
Exercise 2.3 Generate odd numbers......................
.81
Exercise 2.4 Store odd numbers in a list..................
.81
Exercise 2.5 Generate odd numbers by a list comprehension..
82
Exercise 2.6 Make a table of function values..............
..82
Exercise 2.7 Store numbers in lists.....................
...82
Exercise 2.8 Work with a list...........................
..82
Exercise 2.9 Simulate operations on lists by hand.........
..82
Exercise 2.10 Generate equally spaced coordinates.......
....82
Exercise 2.11 Use a list comprehension to solve Exer.2.10..
...82
xxi
xxii
List of Exercises
Exercise 2.12 Compute a mathematical sum................
.83
Exercise 2.13 Use a for loop in Exer.2.12.................
..83
Exercise 2.14 Condense the program in Exer.2.13..........
..83
Exercise 2.15 Compute a polynomial via a product..........
.83
Exercise 2.16 Simulate a program by hand.................
.84
Exercise 2.17 Explore the Python Library Reference........
..84
Exercise 2.18 Implement the sum function................
...84
Exercise 2.19 Index a nested lists......................
....85
Exercise 2.20 Construct a double for loop over a nested list.
...85
Exercise 2.21 Store data in lists in Exercise 2.2..........
....85
Exercise 2.22 Store data from Exer.2.7 in a nested list.....
..85
Exercise 2.23 Convert nested list comprehensions to nested
standard loops...............................85
Exercise 2.24 Demonstrate list functionality...........
......86
Exercise 2.25 Values of boolean expressions.............
.....86
Exercise 2.26 Explore roundoﬀ errors from a large number of
inverse operations............................86
Exercise 2.27 Explore what zero can be on a computer........
86
Exercise 2.28 Compare two real numbers on a computer......8
7
Exercise 2.29 Interpret a code.........................
....87
Exercise 2.30 Explore problems with inaccurate indentatio
n...88
Exercise 2.31 Simulate nested loops by hand..............
...88
Exercise 2.32 Explore punctuation in Python programs.....
..89
Exercise 2.33 Investigate a for loop over a changing list...
....89
Exercise 3.1 Write a Fahrenheit–Celsius conversion functi
on..116
Exercise 3.2 Write the program in Exer.2.12 as a function...
116
Exercise 3.3 Compute the area of an arbitrary triangle.....
..117
Exercise 3.4 Compute the length of a path.................
117
Exercise 3.5 Approximate
π
..............................117
Exercise 3.6 Write some simple functions................
...117
Exercise 3.7 Approximate a function by a sum of sines.......
118
Exercise 3.8 Implement a Gaussian function..............
..118
Exercise 3.9 Make a function of the formula in Exer.1.13....
118
Exercise 3.10 Write a function for numerical diﬀerentiatio
n....119
Exercise 3.11 Write a function for numerical integration..
.....119
Exercise 3.12 Improve the integration in Exer.3.11.......
....119
Exercise 3.13 Generalize the integration formula in Exer.3
.12.119
Exercise 3.14 Implement the factorial function..........
.....120
Exercise 3.15 Compute velocity and acceleration from posit
ion
data;one dimension..........................120
Exercise 3.16 Compute velocity and acceleration from posit
ion
data;two dimensions.........................120
Exercise 3.17 Find the max and min values of a function......
121
Exercise 3.18 Find the max/min elements in a list..........
..121
Exercise 3.19 Express a step function as a Python function..
..122
List of Exercises
xxiii
Exercise 3.20 Rewrite a mathematical function...........
....122
Exercise 3.21 Make a table for approximations of
cos
x
........122
Exercise 3.22 Write a sort function for a list of 4tuples...
....123
Exercise 3.23 Find prime numbers.......................
...124
Exercise 3.24 Explain why a program works................
.124
Exercise 3.25 Resolve a problem with a function...........
..124
Exercise 3.26 Use None in keyword arguments..............
.124
Exercise 3.27 Determine the types of some objects.........
..125
Exercise 3.28 Explain if vs.elif.......................
.....125
Exercise 3.29 Find an error in a program..................
..126
Exercise 3.30 Find programming errors..................
...126
Exercise 4.1 Make an interactive program................
..170
Exercise 4.2 Read from the command line in Exer.4.1.......1
70
Exercise 4.3 Use exceptions in Exer.4.2.................
...170
Exercise 4.4 Read input from the keyboard................
.170
Exercise 4.5 Read input from the command line.............
170
Exercise 4.6 Prompt the user for input to a formula.........
170
Exercise 4.7 Read command line input a formula............
171
Exercise 4.8 Make the program from Exer.4.7 safer.........
171
Exercise 4.9 Test more in the program from Exer.4.7........
171
Exercise 4.10 Raise an exception in Exer.4.9.............
...171
Exercise 4.11 Compute the distance it takes to stop a car....
.171
Exercise 4.12 Look up calendar functionality.............
...171
Exercise 4.13 Use the StringFunction tool...............
....171
Exercise 4.14 Extend a program from Ch.4.2.1.............
.172
Exercise 4.15 Why we test for speciﬁc exception types......
..172
Exercise 4.16 Make a simple module......................
..172
Exercise 4.17 Make a useful main program for Exer.4.16.....
.172
Exercise 4.18 Make a module in Exer.3.7..................
.172
Exercise 4.19 Extend the module from Exer.4.18...........
.173
Exercise 4.20 Use options and values in Exer.4.19.........
..173
Exercise 4.21 Check if mathematical identities hold on a
computer...................................173
Exercise 4.22 Improve input to the program in Exer.4.21....
.173
Exercise 4.23 Apply the program from Exer.4.22...........
.174
Exercise 4.24 Compute the binomial distribution.........
....174
Exercise 4.25 Apply the binomial distribution...........
....175
Exercise 4.26 Compute probabilities with the Poisson
distribution.................................175
Exercise 5.1 Fill lists with function values.............
.....229
Exercise 5.2 Fill arrays;loop version..................
.....230
Exercise 5.3 Fill arrays;vectorized version............
......230
Exercise 5.4 Apply a function to a vector.................
.230
Exercise 5.5 Simulate by hand a vectorized expression.....
..230
Exercise 5.6 Demonstrate array slicing.................
....230
xxiv
List of Exercises
Exercise 5.7 Use array computing in the example from
Chap.2.6.2.................................231
Exercise 5.8 Plot a formula............................
...231
Exercise 5.9 Plot a formula for several parameters........
...231
Exercise 5.10 Specify the
x
and
y
axes in Exer.5.9...........231
Exercise 5.11 Plot exact and inexact Fahrenheit–Celsius
formulas....................................231
Exercise 5.12 Plot the trajectory of a ball...............
....231
Exercise 5.13 Implement Lagrange’s interpolation formula.
....231
Exercise 5.14 Plot the polynomial in Exer.5.13...........
...232
Exercise 5.15 Plot a wave packet........................
...233
Exercise 5.16 Use pyreport in Exer.5.15.................
...233
Exercise 5.17 Judge a plot.............................
....233
Exercise 5.18 Plot the viscosity of water................
....233
Exercise 5.19 Explore a function graphically............
.....234
Exercise 5.20 Plot Taylor polynomial approximations to
sin
x
..234
Exercise 5.21 Animate a wave packet.....................
..234
Exercise 5.22 Animate a smoothed Heaviside function......
..235
Exercise 5.23 Animate twoscale temperature variations..
.....235
Exercise 5.24 Improve the solution in Exer.5.23..........
...236
Exercise 5.25 Animate a sequence of approximations to
π
.....236
Exercise 5.26 Animate a planet’s orbit..................
....236
Exercise 5.27 Animate the evolution of Taylor polynomials.
...237
Exercise 5.28 Plot the velocity proﬁle for pipeﬂow........
....238
Exercise 5.29 Plot the functions from Exer.3.7...........
...238
Exercise 5.30 Make a movie of the functions from Exer.3.7...
.238
Exercise 5.31 Plot functions from the command line........
..239
Exercise 5.32 Improve the program from Exericse 5.31......
..239
Exercise 5.33 Demonstrate energy concepts from physics...
...239
Exercise 5.34 Plot a wlike function....................
....239
Exercise 5.35 Plot a smoothed “hat” function.............
...239
Exercise 5.36 Experience overﬂow in a function...........
...240
Exercise 5.37 Experience less overﬂow in a function.......
...241
Exercise 5.38 Extend Exer.5.4 to a rank 2 array............
.241
Exercise 5.39 Explain why array computations fail........
...241
Exercise 6.1 Read a twocolumn data ﬁle..................
.294
Exercise 6.2 Read a data ﬁle............................
.295
Exercise 6.3 Simplify the implementation of Exer.6.1.....
...295
Exercise 6.4 Fit a polynomial to data....................
..295
Exercise 6.5 Read acceleration data and ﬁnd velocities....
...296
Exercise 6.6 Read acceleration data and plot velocities...
....296
Exercise 6.7 Find velocity from GPS coordinates..........
..297
Exercise 6.8 Make a dictionary from a table...............
.297
Exercise 6.9 Explore syntax diﬀerences:lists vs.dictiona
ries..297
Exercise 6.10 Improve the program from Ch.6.2.4..........
..298
List of Exercises
xxv
Exercise 6.11 Interpret output from a program............
...298
Exercise 6.12 Make a dictionary........................
....298
Exercise 6.13 Make a nested dictionary..................
...298
Exercise 6.14 Make a nested dictionary from a ﬁle..........
..299
Exercise 6.15 Compute the area of a triangle..............
..299
Exercise 6.16 Compare data structures for polynomials....
...299
Exercise 6.17 Compute the derivative of a polynomial......
..299
Exercise 6.18 Generalize the program from Ch.6.2.6.......
..300
Exercise 6.19 Write function data to ﬁle.................
...300
Exercise 6.20 Specify functions on the command line.......
..300
Exercise 6.21 Interpret function speciﬁcations.........
.......301
Exercise 6.22 Compare average temperatures in cities.....
....301
Exercise 6.23 Try Word or OpenOﬃce to write a program.....30
2
Exercise 6.24 Evaluate objects in a boolean context.......
...302
Exercise 6.25 Generate an HTML report...................
.303
Exercise 6.26 Fit a polynomial to experimental data.......
...303
Exercise 6.27 Generate an HTML report with ﬁgures.........
304
Exercise 6.28 Extract information from a weather page.....
..304
Exercise 6.29 Compare alternative weather forecasts.....
.....304
Exercise 6.30 Improve the output in Exercise 6.29.........
...304
Exercise 7.1 Make a function class......................
..359
Exercise 7.2 Make a very simple class....................
..359
Exercise 7.3 Extend the class from Ch.7.2.1..............
..359
Exercise 7.4 Make classes for a rectangle and a triangle....
..360
Exercise 7.5 Make a class for straight lines..............
...360
Exercise 7.6 Improve the constructor in Exer.7.5.........
..360
Exercise 7.7 Make a class for quadratic functions.........
...360
Exercise 7.8 Make a class for linear springs..............
...361
Exercise 7.9 Implement code from Exer.5.13 as a class......
361
Exercise 7.10 A very simple “Hello,World!” class.........
....361
Exercise 7.11 Use special methods in Exer.7.1............
...361
Exercise 7.12 Make a class for nonlinear springs..........
....361
Exercise 7.13 Extend the class from Ch.7.2.1.............
...362
Exercise 7.14 Implement a class for numerical diﬀerentatio
n...362
Exercise 7.15 Verify a program.........................
....363
Exercise 7.16 Test methods for numerical diﬀerentation...
....363
Exercise 7.17 Modify a class for numerical diﬀerentiation.
.....363
Exercise 7.18 Make a class for summation of series.........
..364
Exercise 7.19 Apply the diﬀerentiation class from Ch.7.3.2
....364
Exercise 7.20 Use classes for computing inverse functions.
.....364
Exercise 7.21 Vectorize a class for numerical integration.
......365
Exercise 7.22 Speed up repeated integral calculations....
.....365
Exercise 7.23 Apply a polynomial class..................
...366
Exercise 7.24 Find a bug in a class for polynomials.........
..366
Exercise 7.25 Subtraction of polynomials...............
.....366
xxvi
List of Exercises
Exercise 7.26 Represent a polynomial by an array..........
..367
Exercise 7.27 Vectorize a class for polynomials..........
.....367
Exercise 7.28 Use a dict to hold polynomial coeﬃcients;add.
..367
Exercise 7.29 Use a dict to hold polynomial coeﬃcients;mul.
..367
Exercise 7.30 Extend class Vec2D to work with lists/tuples.
...368
Exercise 7.31 Extend class Vec2D to 3D vectors............
..368
Exercise 7.32 Use NumPy arrays in class Vec2D.............
368
Exercise 7.33 Use classes in the program from Ch.6.6.2.....
..369
Exercise 7.34 Use a class in Exer.6.25...................
...369
Exercise 7.35 Apply the class from Exer.7.34 interactively
....370
Exercise 7.36 Find local and global extrema of a function...
..370
Exercise 7.37 Improve the accuracy in Exer.7.36..........
...372
Exercise 7.38 Find the optimal production for a company....
.372
Exercise 7.39 Extend the program from Exer.7.38..........
.373
Exercise 7.40 Model the economy of ﬁshing................
..374
Exercise 8.1 Flip a coin
N
times..........................421
Exercise 8.2 Compute a probability.....................
...421
Exercise 8.3 Choose random colors......................
..421
Exercise 8.4 Draw balls from a hat.......................
.422
Exercise 8.5 Probabilities of rolling dice..............
......422
Exercise 8.6 Estimate the probability in a dice game.......
..422
Exercise 8.7 Compute the probability of hands of cards.....
.422
Exercise 8.8 Decide if a dice game is fair.................
..422
Exercise 8.9 Adjust the game in Exer.8.8.................
.422
Exercise 8.10 Compare two playing strategies............
....423
Exercise 8.11 Solve Exercise 8.10 with diﬀerent no.of dice.
....423
Exercise 8.12 Extend Exercise 8.11.....................
....423
Exercise 8.13 Investigate the winning chances of some games
..423
Exercise 8.14 Probabilities of throwing two dice.........
.....424
Exercise 8.15 Play with vectorized boolean expressions...
.....424
Exercise 8.16 Vectorize the program from Exer.8.1........
...424
Exercise 8.17 Vectorize the code in Exer.8.2.............
...424
Exercise 8.18 Throw dice and compute a small probability...
.425
Exercise 8.19 Diﬀerence equation for random numbers......
..425
Exercise 8.20 Make a class for drawing balls from a hat......
.425
Exercise 8.21 Independent vs.dependent random numbers...
.426
Exercise 8.22 Compute the probability of ﬂipping a coin....
..426
Exercise 8.23 Extend Exer.8.22........................
....426
Exercise 8.24 Simulate the problems in Exer.4.25.........
...427
Exercise 8.25 Simulate a poker game.....................
..427
Exercise 8.26 Write a nonvectorized version of a code.....
...427
Exercise 8.27 Estimate growth in a simulation model.......
..427
Exercise 8.28 Investigate guessing strategies for Ch.8.4.
1.....428
Exercise 8.29 Make a vectorized solution to Exer.8.8......
...428
Exercise 8.30 Compute
π
by a Monte Carlo method..........428
List of Exercises
xxvii
Exercise 8.31 Do a variant of Exer.8.30..................
...428
Exercise 8.32 Compute
π
by a random sum.................428
Exercise 8.33 1D random walk with drift..................
..429
Exercise 8.34 1D random walk until a point is hit...........
.429
Exercise 8.35 Make a class for 2D random walk..............
429
Exercise 8.36 Vectorize the class code from Exer.8.35.....
...430
Exercise 8.37 2D random walk with walls;scalar version....
..430
Exercise 8.38 2D random walk with walls;vectorized version
..430
Exercise 8.39 Simulate the mixture of gas molecules.......
...430
Exercise 8.40 Simulate the mixture of gas molecules.......
...431
Exercise 8.41 Guess beer brands........................
...431
Exercise 8.42 Simulate stock prices....................
.....431
Exercise 8.43 Compute with option prices in ﬁnance........
..432
Exercise 8.44 Compute velocity and acceleration.........
....433
Exercise 8.45 Numerical diﬀerentiation of noisy signals..
......434
Exercise 8.46 Model the noise in the data in Exer.8.44......
.434
Exercise 8.47 Reduce the noise in Exer.8.44..............
...435
Exercise 8.48 Make a class for diﬀerentiating noisy data...
....435
Exercise 8.49 Find the expected waiting time in traﬃc lights
..436
Exercise 9.1 Demonstrate the magic of inheritance........
..488
Exercise 9.2 Inherit from classes in Ch.9.1..............
...488
Exercise 9.3 Inherit more from classes in Ch.9.1..........
..488
Exercise 9.4 Reverse the class hierarchy from Ch.9.1......
..488
Exercise 9.5 Make circle a subclass of an ellipse..........
...489
Exercise 9.6 Make super and subclass for a point..........
.489
Exercise 9.7 Modify a function class by subclassing.......
...489
Exercise 9.8 Explore the accuracy of diﬀerence formulas...
...490
Exercise 9.9 Implement a subclass......................
...490
Exercise 9.10 Make classes for numerical diﬀerentiation..
.....490
Exercise 9.11 Implement a new subclass for diﬀerentiation.
....490
Exercise 9.12 Understand if a class can be used recursively.
...490
Exercise 9.13 Represent people by a class hierarchy.......
....491
Exercise 9.14 Add a new class in a class hierarchy..........
..492
Exercise 9.15 Change the user interface of a class hierarchy
....492
Exercise 9.16 Compute convergence rates of numerical
integration methods..........................492
Exercise 9.17 Add common functionality in a class hierarchy
..493
Exercise 9.18 Make a class hierarchy for root ﬁnding.......
...493
Exercise 9.19 Make a class for drawing an arrow............
.494
Exercise 9.20 Make a class for drawing a person............
..494
Exercise 9.21 Animate a person with waving hands..........
.495
Exercise 9.22 Make a class for drawing a car...............
..495
Exercise 9.23 Make a car roll...........................
...495
Exercise 9.24 Make a calculus calculator class...........
.....495
Exercise 9.25 Extend Exer.9.24........................
....496
xxviii
List of Exercises
Exercise A.1 Determine the limit of a sequence............
..521
Exercise A.2 Determine the limit of a sequence............
..521
Exercise A.3 Experience convergence problems...........
...521
Exercise A.4 Convergence of sequences with
π
as limit.......521
Exercise A.5 Reduce memory usage of diﬀerence equations...
.522
Exercise A.6 Development of a loan over
N
months..........522
Exercise A.7 Solve a system of diﬀerence equations........
..522
Exercise A.8 Extend the model (A.26)–(A.27).............
..522
Exercise A.9 Experiment with the program from Exer.A.8...5
22
Exercise A.10 Change index in a diﬀerence equation........
..523
Exercise A.11 Construct time points from dates...........
...523
Exercise A.12 Solve nonlinear equations by Newton’s method
..523
Exercise A.13 Visualize the convergence of Newton’s method
...524
Exercise A.14 Implement the Secant method...............
..524
Exercise A.15 Test diﬀerent methods for root ﬁnding.......
...525
Exercise A.16 Diﬀerence equations for computing
sin
x
........525
Exercise A.17 Diﬀerence equations for computing
cos
x
........525
Exercise A.18 Make a guitarlike sound..................
....526
Exercise A.19 Damp the bass in a sound ﬁle.................
526
Exercise A.20 Damp the treble in a sound ﬁle...............
.527
Exercise A.21 Demonstrate oscillatory solutions of (A.13)
......527
Exercise A.22 Improve the program from Exer.A.21.........
.527
Exercise A.23 Simulate the price of wheat................
...528
Exercise B.1 Interpolate a discrete function............
.....555
Exercise B.2 Study a function for diﬀerent parameter values
..555
Exercise B.3 Study a function and its derivative..........
...556
Exercise B.4 Use the Trapezoidal method.................
..556
Exercise B.5 Compute a sequence of integrals.............
..557
Exercise B.6 Use the Trapezoidal method.................
..557
Exercise B.7 Trigonometric integrals..................
.....558
Exercise B.8 Plot functions and their derivatives........
....559
Exercise B.9 Use the Trapezoidal method.................
..559
Exercise C.1 Solve a nonhomogeneous linear ODE...........
575
Exercise C.2 Solve a nonlinear ODE......................
.575
Exercise C.3 Solve an ODE for
y
(
x
)
.......................575
Exercise C.4 Experience instability of an ODE............
..576
Exercise C.5 Solve an ODE for the arc length...............
576
Exercise C.6 Solve an ODE with timevarying growth........
576
Exercise D.1 Use a
w
function with a step..................601
Exercise D.2 Make a callback function in Exercise D.1......
..601
Exercise D.3 Improve input to the simulation program......
.601
Exercise E.1 Solve a simple ODE in two ways...............6
33
Exercise E.2 Use the ODESolver hierarchy to solve a simple
ODE.......................................634
Exercise E.3 Solve an ODE for emptying a tank.............6
34
List of Exercises
xxix
Exercise E.4 Logistic growth with timevarying carrying
capacity....................................634
Exercise E.5 Simulate a falling or rising body in a ﬂuid.....
..635
Exercise E.6 Check the solution’s limit in Exer.E.5.......
...636
Exercise E.7 Visualize the diﬀerent forces in Exer.E.5....
...636
Exercise E.8 Solve an ODE until constant solution.........
..636
Exercise E.9 Use classes in Exer.E.8....................
...637
Exercise E.10 Scale away parameters in Exer.E.8..........
..637
Exercise E.11 Use the 4thorder RungeKutta on (C.32).....
..638
Exercise E.12 Compare ODE methods......................
638
Exercise E.13 Compare ODE methods......................
638
Exercise E.14 Solve two coupled ODEs for radioactive decay.
..638
Exercise E.15 Code a 2ndorder RungeKutta method;functio
n 639
Exercise E.16 Code a 2ndorder RungeKutta method;class..
.639
Exercise E.17 Make an ODESolver subclass for Heun’s method.
639
Exercise E.18 Make an ODESolver subclass for the Midpoint
method.....................................639
Exercise E.19 Make an ODESolver subclass for an Adams
Bashforth method............................640
Exercise E.20 Implement the iterated Midpoint method;
function....................................640
Exercise E.21 Implement the iterated Midpoint method;clas
s..640
Exercise E.22 Make an ODESolver subclass for the iterated
Midpoint method............................640
Exercise E.23 Study convergence of numerical methods for
ODEs......................................641
Exercise E.24 Solve an ODE speciﬁed on the command line....6
41
Exercise E.25 Find the body’s position in Exer.E.5........
...641
Exercise E.26 Add the eﬀect of air resistance on a ball......
..642
Exercise E.27 Solve an ODE system for an electric circuit...
..642
Exercise E.28 Compare methods for solving (E.73)–(E.74)..
...643
Exercise E.29 Explore predatorprey population interacti
ons...643
Exercise E.30 Formulate a 2ndorder ODE as a system........
644
Exercise E.31 Solve the system in Exer.E.30 in a special case
..645
Exercise E.32 Enhance the code from Exer.E.31............
.646
Exercise E.33 Make a tool for analyzing oscillatory solutio
ns...648
Exercise E.34 Replace functions by class in Exer.E.32.....
...648
Exercise E.35 Allow ﬂexible choice of functions in Exer.E.3
4..652
Exercise E.36 Use the modules from Exer.E.34 and E.35......
652
Exercise E.37 Use the modules from Exer.E.34 and E.35......
653
Computing with Formulas
1
Our ﬁrst examples on computer programming involve programs
that
evaluate mathematical formulas.You will learn how to write
and run
a Python program,how to work with variables,how to compute w
ith
mathematical functions such as
e
x
and
sin
x
,and how to use Python
for interactive calculations.
We assume that you are somewhat familiar with computers so th
at
you know what ﬁles and folders
1
are,how you move between folders,
how you change ﬁle and folder names,and how you write text and
save
it in a ﬁle.
All the program examples associated with this chapter can be
found
as ﬁles in the folder
src/formulas
.We refer to the preface for how to
download the folder tree
src
containing all the program ﬁles for this
book.
1.1 The First Programming Encounter:A Formula
The ﬁrst formula we shall consider concerns the vertical mot
ion of a
ball thrown up in the air.FromNewton’s second law of motion o
ne can
set up a mathematical model for the motion of the ball and ﬁnd t
hat
the vertical position of the ball,called
y
,varies with time
t
according
to the following formula
2
:
y
(
t
) =
v
0
t
−
1
2
gt
2
.
(1.1)
1
Another frequent word for folder is directory.
2
This formula neglects air resistance,which is usually smal
l unless
v
0
is large – see
Exercise 1.11.
1
2
1 Computing with Formulas
Here,
v
0
is the initial velocity of the ball,
g
is the acceleration of gravity,
and
t
is time.Observe that the
y
axis is chosen such that the ball starts
at
y
= 0
when
t
= 0
.
To get an overview of the time it takes for the ball to move upwa
rds
and return to
y
= 0
again,we can look for solutions to the equation
y
= 0
:
v
0
t
−
1
2
gt
2
=
t
(
v
0
−
1
2
gt
) = 0
⇒
t
= 0
or
t
= 2
v
0
/g.
That is,the ball returns after
2
v
0
/g
seconds,and it is therefore rea
sonable to restrict the interest of (1.1) to
t
∈
[0
,
2
v
0
/g
]
.
1.1.1 Using a Program as a Calculator
Our ﬁrst program will evaluate (1.1) for a speciﬁc choice of
v
0
,
g
,and
t
.Choosing
v
0
= 5
m/s and
g
= 9
.
81
m/s
2
makes the ball come back
after
t
= 2
v
0
/g
≈
1
s.This means that we are basically interested in
the time interval
[0
,
1]
.Say we want to compute the height of the ball
at time
t
= 0
.
6
s.From (1.1) we have
y
= 5
0
.
6
−
1
2
9
.
81
0
.
6
2
This arithmetic expression can be evaluated and its value ca
n be
printed by a very simple oneline Python program:
print 5*0.6  0.5*9.81*0.6**2
The four standard arithmetic operators are written as
+
,

,
*
,and
/
in Python and most other computer languages.The exponentia
tion
employs a double asterisk notation in Python,e.g.,
0
.
6
2
is written as
0.6**2
.
Our task now is to create the program and run it,and this will b
e
described next.
1.1.2 About Programs and Programming
A computer programis just a sequence of instructions to the c
omputer,
written in a computer language.Most computer languages loo
k some
what similar to English,but they are very much simpler.The n
umber
of words and associated instructions is very limited,so to p
erform a
complicated operation we must combine a large number of diﬀe
rent
types of instructions.The program text,containing the seq
uence of
instructions,is stored in one or more ﬁles.The computer can
only do
exactly what the program tells the computer to do.
1.1 The First Programming Encounter:A Formula
3
Another perception of the word “program” is a ﬁle that can be r
un
(“doubleclicked”) to perform a task.Sometimes this is a ﬁl
e with tex
tual instructions (which is the case with Python),and somet
imes this
ﬁle is a translation of all the program text to a more eﬃcient a
nd
computerfriendly language that is quite diﬃcult to read fo
r a human.
All the programs in this chapter consist of short text stored
in a single
ﬁle.Other programs that you have used frequently,for insta
nce Fire
fox or Internet Explorer for reading web pages,consist of pr
ogram text
distributed over a large number of ﬁles,written by a large nu
mber of
people over many years.One single ﬁle contains the machine
eﬃcient
translation of the whole program,and this is normally the ﬁl
e that
you “doubleclick” on when starting the program.In general
,the word
“program” means either this single ﬁle or the collection of ﬁ
les with
textual instructions.
Programming is obviously about writing programs,but this p
rocess
is more than writing the correct instructions in a ﬁle.First
,we must
understand how a problem can be solved by giving a sequence of
in
structions to the computer.This is usually the most diﬃcult
thing with
programming.Second,we must express this sequence of instr
uctions
correctly in a computer language and store the correspondin
g text in a
ﬁle (the program).Third,we must run the program,check the v
alidity
of the results,and usually enter a fourth phase where errors
in the pro
gram must be found and corrected.Mastering this process req
uires a
lot of training,which implies making a large number of progr
ams (ex
ercises in this book,for instance) and getting the programs
to work.
1.1.3 Tools for Writing Programs
Since programs consist of plain text,we need to write this te
xt with the
help of another programthat can store the text in a ﬁle.You ha
ve most
likely extensive experience with writing text on a computer
,but for
writing your own programs you need special programs,called
editors
,
which preserve exactly the characters you type.The widespr
ead word
processors,Microsoft Word being a primary example
3
,are aimed at
producing nicelooking reports.These programs
format
the text and
are
not
good tools for writing your own programs,even though they ca
n
save the document in a pure text format.Spaces are often impo
rtant in
Python programs,and
editors
for plain text give you complete control
of the spaces and all other characters in the program ﬁle.
3
Other examples are OpenOﬃce,TextEdit,iWork Pages,and BBE
dit.Chapter 6.1.3
gives some insight into why such programs are not suitable fo
r writing your own
Python programs.
4
1 Computing with Formulas
Emacs,XEmacs,Vim,and Gedit are popular editors for writin
g pro
grams on Linux or Unix systems,including Mac
4
computers.On Win
dows we recommend Notepad++ or the Window versions of Emacs,
Vim,or Gedit.None of these programs are part of a standard Wi
ndows
installation.
A special editor for Python programs comes with the Python so
ft
ware.This editor is called Idle and is usually installed und
er the name
idle
(or
idlepython
) on Linux/Unix and Mac.On Windows,it is
reachable from the Python entry in the Start menu.Idle has a g
entle
learning curve,but is mainly restricted to writing Python p
rograms.
Completely general editors,such as Emacs and Vim,have a ste
eper
learning curve and can be used for any text ﬁles,including re
ports in
student projects.
More advanced development environments also exist for Pyth
on.For
numerical programming the Spyder software is of particular
interest as
it provides a graphical environment much like that of Matlab
.
1.1.4 Using Idle to Write the Program
Let us explain in detail how we can use Idle to write our onelin
e
program from Chapter 1.1.1.Idle may not become your favorit
e editor
for writing Python programs,yet we recommend to follow the s
teps
below to get in touch with Idle and try it out.You can simply re
place
the Idle instructions by similar actions in your favorite ed
itor,Emacs
for instance.
First,create a folder where your Python programs can be loca
ted.
Here we choose a folder name
py1st
under your home folder (note
that the third character is the number 1,not the letter l – the
name
reﬂects your 1st try of Python).To write and run Python progr
ams,
you will need a
terminal
window on Linux/Unix or Mac,sometimes
called a
console
window,or an
MSDOS
window or
command prompt
on
Windows.Launch such a window and use the
cd
(change directory)
command to move to the
py1st
folder.If you have not made the folder
with a graphical ﬁle & folder manager you must create the fold
er by
the command
mkdir py1st
(
mkdir
stands for make directory).
The next step is to start Idle.This can be done by writing
idle&
(Linux) or
start idle
(Windows) in the terminal window.Alterna
tively,you can launch Idle from the Start menu on Windows.Fi
g
ure 1.1 displays a terminal window where we create the folder
,move
to the folder,and start Idle
5
.
4
On Mac,you may want to download a more “Maclike” editor such
as the Really
Simple Text program.
5
The ampersand after
idle
is Linux speciﬁc.On Windows you have to write
start
idle
instead.The ampersand postﬁx or the
start
preﬁx makes it possible to con
tinue with other commands in the terminal window while the pr
ogram,here Idle,
1.1 The First Programming Encounter:A Formula
5
Fig.1.1
A terminal window on a Linux/Unix/Mac machine where we creat
e a folder
(
mkdir
),move to the folder (
cd
),and start Idle.
If a window now appears on the screen,with “Python Shell” in t
he
title bar of the window,go to its File menu and choose New Wind
ow.
The window that now pops up is the Idle editor (having the wind
ow
name “Untitled”).Move the cursor inside this window and wri
te the
line
print 5*0.6  0.5*9.81*0.6**2
followed by pressing the Return key.The Idle window looks as
in Fig
ure 1.2.
Fig.1.2
An Idle editor window containing our ﬁrst oneline program.
Your program is now in the Idle editor,but before you can run i
t,
the program text must be saved in a ﬁle.Choose File and then Sa
ve
As.As usual,such a command launches a new window where you ca
n
ﬁll in the name of the ﬁle where the program is to be stored.And
as always,you must ﬁrst check that you are in the right folder
,or
directory which is Idle’s word for the same thing.The upper l
ine in
the ﬁle dialog window contains the folder name.Clicking on t
he bar
to the right (after the directory/folder name),gives a poss
ibility to
is running.This is important for program testing where we of
ten do a lot of edit
andrun cycles,which means that we frequently switch betwe
en the editor and the
terminal window.
6
1 Computing with Formulas
move upwards in the folder hierarchy,and clicking on the fol
der icon
to the right of the bar,moves just one folder upwards.To go do
wn
in the folder tree,you simply doubleclick a folder icon in t
he main
window of this dialog.You must now navigate to the
py1st
folder under
your home folder.If you started Idle from the terminal windo
w,there
is no need to navigate and change folder.Simply ﬁll in the nam
e of
the program.Any name will do,but we suggest that you choose t
he
name
ball_numbers.py
because this name is compatible with what we
use later in this book.The ﬁle extension
.py
is common for Python
programs,but not strictly required
6
.
Press the Save button and move back to the terminal window.Ma
ke
sure you have a new ﬁle
ball_numbers.py
here,by running the com
mand
ls
(on Linux/Unix and Mac) or
dir
(on Windows).The output
should be a text containing the name of the program ﬁle.You ca
n now
jump to the paragraph “How to Run the Program”,but it might be
a
good idea to read the warning below ﬁrst.
Warning About Typing Program Text.
Even though a program is just
a text,there is one major diﬀerence between a text in a progra
m and
a text intended to be read by a human.When a human reads a text,
she or he is able to understand the message of the text even if t
he text
is not perfectly precise or if there are grammar errors.If ou
r oneline
program was expressed as
write 5*0.6  0.5*9.81*0.6^2
most humans would interpret
write
and
print
as the same thing,and
many would also interpret
6^2
as
6
2
.In the Python language,however,
write
is a grammar error and
6^2
means an operation very diﬀerent
from the exponentiation
6**2
.Our communication with a computer
through a programmust be perfectly precise without a single
grammar
error
7
.The computer will only do exactly what we tell it to do.Any
error in the program,however small,may aﬀect the program.T
here is
a chance that we will never notice it,but most often an error c
auses
the program to stop or produce wrong results.The conclusion
is that
computers have a much more pedantic attitude to language tha
n what
(most) humans have.
Now you understand why any programtext must be carefully typ
ed,
paying attention to the correctness of every character.If y
ou try out
programtexts fromthis book,make sure that you type themin
exactly
as you see them
in the book.Blanks,for instance,are often important
in Python,so it is a good habit to always count them and type th
em
6
Some editors,like Emacs,have many features that make it eas
ier to write Python
programs,but these features will not be automatically avai
lable unless the program
ﬁle has a
.py
extension.
7
“Programming demands signiﬁcantly higher standard of accu
racy.Things don’t
simply have to make sense to another human being,they must ma
ke sense to a
computer.” –Donald Knuth [4,p.18],computer scientist,19
38.
1.1 The First Programming Encounter:A Formula
7
in correctly.Any attempt not to follow this advice will caus
e you frus
trations,sweat,and maybe even tears.
1.1.5 How to Run the Program
The oneline program above is stored in a ﬁle with name
ball_numbers.py
.To run the program,you need to be in a termi
nal window and in the folder where the
ball_numbers.py
ﬁle resides.
The program is run by writing the command
python ball_numbers.py
in the terminal window
8
:
Terminal
Unix/DOS> python ball_numbers.py
1.2342
The programimmediately responds with printing the result o
f its calcu
lation,and the output appears on the next line in the termina
l window.
In this book we use the prompt
Unix/DOS>
to indicate a command line in
a Linux,Unix,Mac,or DOS terminal window (a command line mean
s
that we can run Unix or DOS commands,such as
cd
and
python
).On
your machine,you will likely see a diﬀerent prompt.Figure 1
.3 shows
what the whole terminal window may look like after having run
the
program.
Fig.1.3
A terminal window on a Linux/Unix/Mac machine where we run ou
r ﬁrst
oneline Python program.
From your previous experience with computers you are probab
ly
used to doubleclick on icons to run programs.Python progra
ms can
also be run that way,but programmers usually ﬁnd it more conv
enient
to run programs by typing commands in a terminal window.Why t
his
is so will be evident later when you have more programming exp
erience.
For now,simply accept that you are going to be a programmer,a
nd
that commands in a terminal window is an eﬃcient way to work wi
th
the computer.
8
There are other ways of running Python programs,as explaine
d in Appendix G.1.
8
1 Computing with Formulas
Suppose you want to evaluate (1.1) for
v
0
= 1
and
t
= 0
.
1
.This is
easy:move the cursor to the Idle editor window,edit the prog
ram text
to
print 1*0.1  0.5*9.81*0.1**2
Save the ﬁle,move back to the terminal window and run the prog
ram
as before:
Terminal
Unix/DOS> python ball_numbers.py
0.05095
We see that the result of the calculation has changed,as expe
cted.
1.1.6 Verifying the Result
We should
always
carefully control that the output of a computer pro
gram is correct.You will experience that in most of the cases
,at least
until you are an experienced programmer,the output is wrong
,and
you have to search for errors.In the present application we c
an simply
use a calculator to control the program.Setting
t
= 0
.
6
and
v
0
= 5
in
the formula,the calculator conﬁrms that 1.2342 is the corre
ct solution
to our mathematical problem.
1.1.7 Using Variables
When we want to evaluate
y
(
t
)
for many values of
t
,we must modify the
t
value at two places in our program.Changing another paramet
er,like
v
0
,is in principle straightforward,but in practice it is easy
to modify
the wrong number.Such modiﬁcations would be simpler to perf
orm
if we express our formula in terms of variables,i.e.,symbol
s,rather
than numerical values.Most programming languages,Python
included,
have variables similar to the concept of variables in mathem
atics.This
means that we can deﬁne
v0
,
g
,
t
,and
y
as variables in the program,
initialize the former three with numerical values,and comb
ine these
three variables to the desired righthand side expression i
n (1.1),and
assign the result to the variable
y
.
The alternative version of our program,where we use variabl
es,may
be written as this text:
v0 = 5
g = 9.81
t = 0.6
y = v0*t  0.5*g*t**2
print y
1.1 The First Programming Encounter:A Formula
9
Figure 1.4 displays what the program looks like in the Idle ed
itor win
dow.Variables in Python are deﬁned by setting a name (here
v0
,
g
,
t
,or
y
) equal to a numerical value or an expression involving alrea
dy
deﬁned variables.
Fig.1.4
An Idle editor windowcontaining a multiline programwith s
everal variables.
Note that this second program is much easier to read because i
t is
closer to the mathematical notation used in the formula (1.1
).The pro
gram is also safer to modify,because we clearly see what each
number
is when there is a name associated with it.In particular,we c
an change
t
at one place only (the line
t = 0.6
) and not two as was required in
the previous program.
We store the program text in a ﬁle
ball_variables.py
.Running the
program,
Terminal
Unix/DOS> python ball_variables.py
results in the correct output
1.2342
.
1.1.8 Names of Variables
Introducing variables with descriptive names,close to tho
se in the
mathematical problem we are going to solve,is considered im
portant
for the readability and reliability (correctness) of the pr
ogram.Vari
able names can contain any lower or upper case letter,the num
bers
from 0 to 9,and underscore,but the ﬁrst character cannot be a
num
ber.Python distinguishes between upper and lower case,so
X
is always
diﬀerent from
x
.Here are a few examples on alternative variable names
in the present example
9
:
9
In this book we shall adopt the rule that variable names have l
ower case letters
where words are separated by an underscore.The ﬁrst two decl
ared variables have
this form.
10
1 Computing with Formulas
initial_velocity = 5
acceleration_of_gravity = 9.81
TIME = 0.6
VerticalPositionOfBall = initial_velocity*TIME \
0.5*acceleration_of_gravity*TIME**2
print VerticalPositionOfBall
With such long variables names,the code for evaluating the f
Enter the password to open this PDF file:
File name:

File size:

Title:

Author:

Subject:

Keywords:

Creation Date:

Modification Date:

Creator:

PDF Producer:

PDF Version:

Page Count:

Preparing document for printing…
0%
Σχόλια 0
Συνδεθείτε για να κοινοποιήσετε σχόλιο