Introduction To Scientific Programming With Python Joakim Sundnes PDF Download
Introduction To Scientific Programming With Python Joakim Sundnes PDF Download
https://textbookfull.com/product/introduction-to-scientific-programming-with-python-joakim-sundnes/
DOWNLOAD EBOOK
Introduction to Scientific Programming with Python Joakim
Sundnes pdf download
Available Formats
Joakim Sundnes
Introduction
to Scientific
Programming
with Python
Simula SpringerBriefs on Computing
Volume 6
Editor-in-Chief
Aslak Tveito, Fornebu, Norway
Series Editors
Are Magnus Bruaset, Fornebu, Norway
Kimberly Claffy, San Diego, USA
Magne Jørgensen, Fornebu, Norway
Olav Lysne, Fornebu, Norway
Andrew McCulloch, La Jolla, USA
Fabian Theis, Neuherberg, Germany
Karen Willcox, Cambridge, USA
Andreas Zeller, Saarbrücken, Germany
Springer and Simula have launched a new book series, Simula SpringerBriefs on
Computing, which aims to provide introductions to select research in computing.
The series presents both a state-of-the-art disciplinary overview and raises essential
critical questions in the field. Published by SpringerOpen, all Simula SpringerBriefs
on Computing are open access, allowing for faster sharing and wider dissemination
of knowledge.
Simula Research Laboratory is a leading Norwegian research organization which
specializes in computing. The book series will provide introductory volumes on
the main topics within Simula’s expertise, including communications technology,
software engineering and scientific computing.
By publishing the Simula SpringerBriefs on Computing, Simula Research
Laboratory acts on its mandate of emphasizing research education. Books in this
series are published only by invitation from a member of the editorial board.
Introduction
to Scientific
Programming
with Python
Joakim Sundnes
Simula Research Laboratory
Lysaker, Norway
Mathematics Subject Classification (2010): 65D15, 65D25, 65D30, 68-01, 68N01, 68N19, 97-04
© The Editor(s) (if applicable) and the Author(s) 2020. This book is an open access publication.
Open Access This book is licensed under the terms of the Creative Commons Attribution 4.0
International License (http://creativecommons.org/licenses/by/4.0/), which permits use, sharing, adap-
tation, distribution and reproduction in any medium or format, as long as you give appropriate credit to
the original author(s) and the source, provide a link to the Creative Commons license and indicate if
changes were made.
The images or other third party material in this book are included in the book's Creative Commons
license, unless indicated otherwise in a credit line to the material. If material is not included in the book's
Creative Commons license and your intended use is not permitted by statutory regulation or exceeds the
permitted use, you will need to obtain permission directly from the copyright holder.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publi-
cation does not imply, even in the absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this
book are believed to be true and accurate at the date of publication. Neither the publisher nor the
authors or the editors give a warranty, expressed or implied, with respect to the material contained herein or
for any errors or omissions that may have been made. The publisher remains neutral with regard to
jurisdictional claims in published maps and institutional affiliations.
This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
Dedicated to the memory of Hans Petter
Langtangen.
Foreword
Dear reader,
Our aim with the series Simula SpringerBriefs on Computing is to provide
compact introductions to selected fields of computing. Entering a new field of
research can be quite demanding for graduate students, postdocs, and experienced
researchers alike: the process often involves reading hundreds of papers, and the
methods, results and notation styles used often vary considerably, which makes for
a time-consuming and potentially frustrating experience. The briefs in this series are
meant to ease the process by introducing and explaining important concepts and
theories in a relatively narrow field, and by posing critical questions on the fun-
damentals of that field. A typical brief in this series should be around 100 pages and
should be well suited as material for a research seminar in a well-defined and
limited area of computing.
We have decided to publish all items in this series under the SpringerOpen
framework, as this will allow authors to use the series to publish an initial version
of their manuscript that could subsequently evolve into a full-scale book on a
broader theme. Since the briefs are freely available online, the authors will not
receive any direct income from the sales; however, remuneration is provided for
every completed manuscript. Briefs are written on the basis of an invitation from a
member of the editorial board. Suggestions for possible topics are most welcome
and can be sent to aslak@simula.no.
vii
Preface
This book was originally written as a set of lecture notes to the book A
Primer on Scientific Programming with Python by Hans Petter Langtangen1 ,
and can be used either as a supplement to that book or on its own, as a com-
pact introduction to scientific programming. Langtangen’s book and these
lecture notes, have formed the core of an introductory course on scientific
programming at the University of Oslo (INF1100/IN1900, 10 ETCS credits).
The course has been running since 2007 and is primarily taken by first-year
students of mathematics, engineering, physics, chemistry, and geosciences.
The writing of these lecture notes, and their subsequent evolution into a
book, were primarily motivated by two factors. The first was that many stu-
dents found the nearly 1000 pages of Langtangen’s book a bit overwhelming
as a first introduction to programming. This effect could be mostly psy-
chological, since the book is well structured and suited for selective study
of chapters and sections, but the student feedback from students still indi-
cated the need for a more compact and (literally) lightweight introduction.
The second factor was that, sadly, Hans Petter Langtangen passed away in
2016, and his book has therefore not been updated to the newest versions
of Python and the various tools introduced in the book. This issue could
also be mostly a mental obstacle, since the differences between the Python
versions are quite small, and only minor edits are needed to make most of
the examples from the original book run on the newest Python platform.
However, the book is intended as an introduction to programming, and when
learning an entirely new topic, any minor inconsistency is a potential source
of confusion. I therefore saw the need for an updated document where all the
code examples would run without any modifications on the most common
Python platforms. That said, in spite of these minor shortcomings as an in-
troductory text, Langtangen’s book is still an excellent resource on scientific
programming in Python. Compared with the present book, it covers a much
1
Hans Petter Langtangen, A Primer on Scientific Programming with Python, 5th
edition, Springer-Verlag, 2016.
ix
x Preface
broader set of topics and includes more examples, more detailed discussions
and explanations, and many more useful programming hints and tips. I highly
recommend it as a supplement to these notes for anyone with ambitions to
become an expert scientific programmer.
The present book was written specifically for the course Introduction to
programming for scientific applications (IN1900) at the University of Oslo. It
follows exactly the same teaching philosophy and general structure as Lang-
tangen’s original book, with the overarching idea that the only way to learn
to program is to write programs. Reading theory is useful, but without actual
programming practice, the value is very limited. The IN1900 course is there-
fore largely based on problem solving and programming exercises, and this
book’s main purpose is to prepare the students for such tasks by providing a
brief introduction to fundamental programming concepts and Python tools.
The presentation style is compact and pragmatic, and includes a large num-
ber of code examples to illustrate how new concepts work and are applied in
practice. The examples are a combination of pieces of code (so-called code
snippets), complete Python programs, and interactive sessions in a Python
shell. Readers are encouraged to run and modify the codes to gain a feel for
how the various programming concepts work. Source code for most of the
examples, as well as Jupyter notebooks for all the chapters, is provided in
the online resources accompanying this book.
The typical reader of the book will be a student of mathematics, physics,
chemistry, or other natural science, and many of the examples will be famil-
iar to these readers. However, the rapidly increasing relevance of data science
means that computations and scientific programming will be of interest to
a growing group of users. No typical data science tools are presented in this
book, but the reader will learn tasks such as reading data from files, sim-
ple text processing, and programming with mathematics and floating point
computations. These are all fundamental building blocks of any data science
application, and they are essential to know before diving into more advanced
and specialized tools.
No prior knowledge of programming is needed to read this book. We start
with some very simple examples to get started with programming and then
move on to introduce fundamental programming concepts such as loops, func-
tions, if-tests, lists, and classes. These generic concepts are supplemented
by more specific and practical tools for scientific programming, primarily
plotting and array-based computations. The book’s overall purpose is to in-
troduce the reader to programming and, in particular, to demonstrate how
programming can be an extremely useful and powerful tool in many branches
of the natural sciences.
Many people have contributed to this book, in particular my colleagues at
Simula Research Laboratory and the University of Oslo. However, the contri-
butions of Professor Hans Petter Langtangen stand head and shoulders above
everyone else. He has been an extremely inspiring teacher, mentor, and col-
league throughout my scientific career; he developed the course that is now
Preface xi
IN1900; and he wrote the book on which these notes are based. Throughout
these lecture notes I have extensively copied ideas, presentation style, and
code examples from his original book, simply because I find them excellent
for introducing programming in a scientific context. If it were not for Hans
Petter I would clearly never have written these notes. I would probably not
be writing this either if he had not, sadly, passed away in 2016 – there would
be no need to, because he would surely have written a far better and more
extensive book himself.
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
xiii
xiv Contents
8 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
8.1 Basics of Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
8.2 Protected Class Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.3 Special Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.4 Example: Automatic Differentiation of Functions . . . . . . . . . . . 127
8.5 Test Functions for Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
8.6 Example: A Polynomial Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Chapter 1
Getting Started with Python
This book teaches the Python programming language, which is one of the
most popular languages for introductory programming courses. An advantage
of Python is that it is a so-called high-level language, with simple and intuitive
syntax that makes it easy to get started. However, although it works well as a
beginner’s language, Python is also suitable for more advanced tasks, and it
is currently one of the most widely used programming languages worldwide.
To actually write and run such a program, Python offers a number of different
options. Throughout this book we will mostly apply the classical program-
ming approach, where a program is written in a text editor and stored as a
file that is then run from the command line window or an integrated devel-
opment environment (IDE). To write and run the "Hello, World!"-program
above, open your favorite editor (Atom, gedit, Emacs etc.), type the given
line and save the file with a suitable filename, for instance, hello.py.1 Then,
open a terminal or an iPython window, navigate to the directory where you
saved the file, and type python hello.py, if you are using a regular terminal,
or run hello.py if you are using iPython. The output Hello, World! should
1
We do not describe the technical details of acquiring and installing Python here,
since this information is platform dependent and becomes outdated very quickly. For up-
dated hints on installing Python, see the web page for the IN1900 course at the University
of Oslo (https://www.uio.no/studier/emner/matnat/ifi/IN1900/index-eng.html),
or to the numerous other resources found online.
© The Author(s) 2020
J. Sundnes, Introduction to Scientific Programming with 1
Python, Simula SpringerBriefs on Computing 6,
https://doi.org/10.1007/978-3-030-50356-7_1
2 1 Getting Started with Python
appear in the terminal right after the command. If you are using an IDE,
it is essentially an editor and an iPython/terminal window combined. For
instance, in the popular Spyder IDE the editor is usually in the upper left
window, while the window in the lower right corner is the iPython window
where you run the program. 2
Although the "Hello, World!"-program could seem like a silly example, it
serves a number of useful purposes. First of all, running this small program
will verify that you have installed Python properly, and that you have in-
stalled the right version. It also introduces the function print, which will be
used virtually every time we program, and it illustrates how we use quotes to
define a string in Python. While print is a word that Python understands,
the words "Hello" and "World" are not. By using the quotes, we tell Python
that it should not try to understand (or interpret) these words, but, rather,
treat them as simple text that, in this case, is to be printed to the screen.
We will come back to this topic in more detail later.
Terminal> ipython
Python 3.7.3 (default, Mar 27 2019, 16:54:48)
Type ’copyright’, ’credits’ or ’license’ for more information
IPython 7.4.0 -- An enhanced Interactive Python.
In [2]:
The two versions python and ipython work largely the same way, but
ipython has a number of additional features and is recommended.
2
For details, see, for instance, https://www.spyder-ide.org/.
1.2 Different Ways to Use Python 3
3
Hans Petter Langtangen, A Primer on Scientific Programming with Python, 5th
edition, Springer-Verlag, 2016.
4 1 Getting Started with Python
Open Access Dieses Kapitel wird unter der Creative Commons Namensnennung 4.0
International Lizenz (http://creativecommons.org/licenses/by/4.0/deed.de) veröffentli-
cht, welche die Nutzung, Vervielfältigung, Bearbeitung, Verbreitung und Wiedergabe
in jeglichem Medium und Format erlaubt, sofern Sie den/die ursprünglichen Autor(en)
und die Quelle ordnungsgemäß nennen, einen Link zur Creative Commons Lizenz
beifügen und angeben, ob Änderungen vorgenommen wurden.
Die in diesem Kapitel enthaltenen Bilder und sonstiges Drittmaterial unterliegen eben-
falls der genannten Creative Commons Lizenz, sofern sich aus der Abbildungsleg-
ende nichts anderes ergibt. Sofern das betreffende Material nicht unter der genannten
Creative Commons Lizenz steht und die betreffende Handlung nicht nach gesetzlichen
Vorschriften erlaubt ist, ist für die oben aufgeführten Weiterverwendungen des Materi-
als die Einwilligung des jeweiligen Rechteinhabers einzuholen.
Chapter 2
Computing with Formulas
In this chapter, we will go one step beyond the Hello, World! example of the
first chapter, and introduce programming with mathematical formulas. Such
formulas are essential parts of most programs written for scientific applica-
tions, and they are also useful for introducing the concept of variables, which
is a fundamental part of all programming languages.
A = P (1 + (r/100))n ,
where P is the initial deposit (the principal), r is the yearly interest rate
given in percent, n is the number of years, and A is the final amount.
The task is now to write a program that computes A for given values of
P , r and n. We could, of course, easily do so with a calculator, but a small
program can be much more flexible and powerful. To evaluate the formula
above, we first need to assign values to P , r and n, and then make the
calculation. Choosing, for instance, P = 100, r = 5.0, and n = 7, a complete
Python program that does the calculation and outputs the result reads
print(100*(1 + 5.0/100)**7)
140.71004226562505
As described in the previous chapter this line can be typed into an inter-
active Python session, or written in an editor and stored in a file, for in-
stance interest0.py. The program is then run with the command python
While most people can read this line quite easily, and interpret it as the
same formula as the one above, it makes no sense as a Python program.
There are multiple errors: write is not a legal Python word in this context,
a comma has another meaning than the decimal point, and the hat does not
mean exponentiation. We have to be extremely accurate with how we write
computer programs, and it takes time and experience to learn this.
The mathematical formula above is evaluated according to the standard
rules. The terms are evaluated one by one, from left to right, with exponentia-
tion performed first and then multiplication and division. We use parentheses
to control the order of the evaluation, just as we do in regular mathemat-
ics. The parentheses around (1 + 5.0/100) means that this sum is evalu-
ated first (to obtain 1.05), and then raised to the power of 7. Forgetting the
parenthesis and writing 1 + 5.0/100**7 will produce a very different result,
just as in mathematics. Because the use of parentheses to group calculations
works exactly as in mathematics, it is not very difficult to understand for
people with a mathematical background. However, when programming more
complicated formulas it is very easy to make mistakes such as forgetting or
misplacing a closing parenthesis. This mistake is probably the most common
source of error when programming mathematical formulas, and it is worth
paying close attention to the order and number of parentheses in the expres-
sions, even for experienced programmers. Getting this principle wrong will
lead to either an error message when the code is run or to a program that
runs fine but produces unexpected results. The first type of error is usually
quite easy to find and fix, but the latter can be much harder.
Although Python is quite strict on spelling and grammar, in programming
terms called the syntax, there is some flexibility. For instance, whitespace
inside a formula does not matter at all. An expression like 5 *2 works just
as well as 5*2. Generally, whitespace in a Python program only matters if it
is at the start of a line, which we will return to later. Otherwise, one should
2.2 Variables and Variable Types 7
This program spans several lines of text and uses variables, but otherwise
performs the same calculations and produces the exact same output as the
one-line program above. Still, the use of variables has a few advantages, even
in this very simple example. One is that the program becomes easier to read,
since the meaning of the numbers becomes more intuitive and the formula
is easier to recognize. Another advantage, which could be more important,
is that it becomes easier to change the value of one of the variables. This
advantage becomes even more obvious in more complex formulas where the
same variable occurs multiple times. Having to change the code in multiple
places each time a new value is needed is guaranteed to introduce errors. If
the same number occurs more than once in a program, it should always be
stored in a variable.
The instructions in the program above are called statements, and are exe-
cuted one by one when the program is run. It is common to have one state-
ment per line, although it is possible to put multiple statements on one line,
separated by semicolons, as in primary = 100; r = 5.0; n=7. For people
new to programming, especially those used to reading mathematics, it is
worth noting the strict sequence in which the lines are executed. In the
mathematical equation above, we first introduced the formula itself, and then
defined and explained the variables used in the formula (P, r, n, and A) on
the next line. This approach is completely standard in mathematics, but it
makes no sense in programming. Programs are executed line by line from the
top, so so all the variables must be defined above the line where they are
used.
The choice of variable names is up to the programmer and, generally, there
is great flexibility in choosing such names. In mathematics, it is common to
use a single letter for a variable, but a variable in a Python program can be
any word containing the letters a–z, A–Z, underscore _ and the digits 0-9, but
it cannot start with a digit. Variable names in Python are also case-sensitive,
8 2 Computing with Formulas
These variable names are arguably more descriptive, but they also make the
formula very long and cumbersome to read. Choosing good variable names
is often a balance between being descriptive and conciseness, and the choice
can be quite important for making a program easy to read and understand.
Writing readable and understandable code is obviously important if you col-
laborate with others who have to understand your code, but it also makes it
easier for you to find errors in the code or develop it further at a later stage.
Choosing good variable names is therefore worthwhile, even if you are the
only person who will ever read your code.
The program above contains two different types of statements; first there
are four assignment statements, which assign values to variables, and then a
single print statement at the end. How these statements work might be quite
intuitive, but the assignment statements are worth looking into in more detail.
In these statements, the expression on the right-hand side of the equality sign
is evaluated first, and then the result is assigned to the variable on the left.
An effect of this execution order is that statements such as the following work
just fine, and are common in programs:
t = 0.6
t = t + 0.1
print(t)
0.7
True
In this code, all the text following the # symbol is treated as a comment
and effectively ignored by Python. Comments are used to explain what the
computer instructions mean, what the variables represent, and how the pro-
grammer reasoned when writing the program. They can be very useful for
increasing readability, but they should not be over-used. Comments that say
no more than the code, for instance, a = 5 # set a to 5, are not very
useful.
All variables have types. So far all the variables we have used have been
numbers, which is also how we are used to thinking of variables in mathe-
matics. However, in a computer program we can have many different kinds of
variables, not just numbers. More precisely, a variable is a name for a Python
object, and all objects have a type. The type of a variable Python is usually
decided automatically based on the value we assign to it. For instance, the
statement n = 7 will create a variable of the type integer, or int, whereas
r = 5.0 will create a variable with type float, representing a floating point
number. We can also have text variables, called strings, which have type str.
For instance, the Hello, World! example above could have been written as
hello = "Hello, World!"
print(hello)
Here we create a variable hello, which automatically gets type str, and then
print the contents of this variable to the screen. The output is exactly the
same as for the first example of Chapter 1.
We can check the type of a variable using the built-in function type:
print(type(hello))
print(type(r))
print(type(primary))
print(type(n))
<class ’str’>
<class ’float’>
<class ’float’>
<class ’int’>
10 2 Computing with Formulas
We see that the output is as expected from the definitions of these variables
above. The word class preceding the types indicates that these types are
defined as classes in Python, a concept we will return to later. It is usually
not necessary to check the type of variables inside a Python program, but it
could be very useful when learning new concepts or if your program produces
errors or unexpected behavior.
We will encounter many more variable types in subsequent chapters. The
type of a variable decides how it can be used, and also determines the effects of
various operations on that variable. The rules for these operations are usually
quite intuitive. For instance, most mathematical operations only work with
variable types that actually represent numbers, or they have a different effect
on other variable types, when this is natural. For an idea of how this works in
Python, think about some simple mathematical operations on text strings.
Which of the following operations do you think are allowed, and what are
the results: (i) adding two strings together, (ii) multiplying a string with
an integer, (iii) multiplying two strings, and (iv) multiplying a string with
a decimal number? After giving some thought to this question, check your
answers by trying them in Python:
hello = "Hello, World!"
print(hello + hello)
print(hello*5)
4
22
<class ’float’>
<class ’float’>
4.0
Of course, using float to convert a string to a number requires that the string
actually be a number. Trying to convert a regular word, as in float(hello)
will make the program stop with an error message. There are numerous other
built-in functions for converting between types, such as int for conversion to
an integer and str for conversion to a string. Throughout this book we will
mostly use the float conversion.
The calculations in the programs above would output a single number, and
simply print this number to the screen. In many cases this solution is fine,
but sometimes we want several numbers or other types of output from a
program. This is easy to do with the print function, by simply putting
several variables inside the parentheses, separated by comma. For instance,
if we want to output both primary and final_amount from the calculation
above, the following line would work:
print(primary,final_amount)
100 140.71004226562505
However, although this line works, the output is not very readable or useful.
Sometimes a better output format or a combination of text and numbers is
more useful, for instance,
After 7 years, 100 EUR has grown to xxx EUR.
There are multiple ways to obtain this result in Python, but the most re-
cent and arguably most convenient is to use so called f-strings, which were
introduced in Python 3.6. If you are using an earlier version of Python, the
following examples will not work, but there are alternative and fairly similar
ways of formatting the text output.
To achieve the output string above, using the f-string formatting, we would
replace the final line of our program by with
print(f"After {n} years, 100 EUR has grown to {amount} EUR.")
There are a couple of things worth noticing here. First, we enclose the output
in quotation marks, just as in the Hello, World! example above, which tells
Python that this is a string. Second, the string is prefixed with the letter f,
which indicates that the string is an f-string that could contain something
12 2 Computing with Formulas
extra. More specifically, the string could contain expressions or variables en-
closed in curly brackets, and we have included two such variables, n and
amount. When Python encounters the curly brackets inside an f-string, it
will evaluate the contents of the curly brackets, which can be an expression
or a variable, and insert the resulting value into the string. The process is
often referred to as string interpolation or variable interpolation, and it ex-
ists in various forms in many programming languages. In our case, Python
will simply insert the current values of the variables n and amount into the
string, but, if desired, we can also include a mathematical expression inside
the brackets, such as
print(f"2+2 = {2+2}")
2+2 = 4
The only requirement for the contents inside the curly brackets is that it
be a valid Python expression that can be evaluated to yield some kind of
value. Throughout this book we will typically use f-string formatting to insert
combining text and numbers, but it may also be used for expressions with
other types of output.
The f-string formatting will often produce nicely formatted output by de-
fault, but sometimes more detailed control of the formatting is desired. For
instance, we might want to control the number of decimal places when out-
putting numbers. This is conveniently achieved by including a format specifier
inside the curly brackets. Consider, for instance, the following code:
t = 1.234567
print(f"Default output gives t = {t}.")
print(f"We can set the precision: t = {t:.2}.")
print(f"Or control the number of decimals: t = {t:.2f}.")
There are many different format specifiers, for controlling the output format
of both numbers and other types of variables. We will use only a small subset
in this book, and primarily to control the formatting of numbers. In addition
to those shown above, the following format specifiers can be useful;
print(f"We may set the space used for the output: t = {t:8.2f}.")
This specifier is used to control the number of decimals, as well as how much
space (the number of characters) used to output the number on the screen.
Here we have specified the number to be output with two decimal places
and a length of eight, including the decimal places. This form of control is
very useful for outputting multiple lines in tabular format, to ensure that the
2.4 Importing Modules 13
columns in the table are properly aligned. A similar feature can be used for
integers:
r = 87
print(f"Integer set to occupy exactly 8 chars of space: r = {r:8d}")
Finally, the generic format specifier g outputs a floating point number in the
most compact form:
a = 786345687.12
b = 1.2345
print(f"Without the format specifier: a = {a}, b = {b}.")
print(f"With the format specifier: a = {a:g}, b = {b:g}.")
False
True
We see that the evaluation works as expected in one case, but not the other,
and this is a general problem when comparing floating point numbers. In most
cases the evaluation works, but in some cases it does not. It is difficult or
impossible to predict when it will not work, and the behavior of the program
thus becomes unpredictable. The solution is to always compare floats by using
a tolerance value, as in
tol = 1e-14
print(abs(v1-1) < tol)
print(abs(v2-1) < tol)
True
True
There is no strict rule for setting the value of the tolerance tol; however, it
should be small enough to be considered insignificant for the application at
hand, but larger than the typical machine precision 10−16 .
Some words are reserved and cannot be used as variables. Although
the choice of variable names is up to the programmer, some names are re-
served in Python and are not allowed to be used. These names are and,
as, assert, break, class, continue, def, del, elif, else, except, exec,
finally, for, from, global, if, import, in, is, lambda, not, or, pass,
print, raise, return, try, with, while, and yield. Memorizing this list is
by no means necessary at this point, and we will use many of these reserved
words in our programs later, so it will become quite natural to not use them
as variable names. However, for programming physics and mathematics, it
could be worth noting lambda, since the Greek letter λ is common in physics
and mathematics formulas. Since Python does not understand Greek letters,
it is common to just spell them out when programming a formula, that is, α
becomes alpha, and so on. However, using this approach for λ will lead to
an error, and the error message might not be very easy to understand. The
problem is easily solved by introducing a small intentional typo and writing
lmbda or similar.
Integer division can cause surprising errors. In Python 2, and many
other programming languages, unintended integer division can sometimes
cause surprising results. In Python 3 this is no longer a problem, so you
are not likely to run into it during this course, but it is worth being aware
of, since many other programming languages behave in this way. Recall from
above that various operations behave differently, depending on the type of the
variable they work on, such as in adding two strings versus adding numbers.
In Python 2, the division operator, /, behaves as in normal division if one
of the two arguments is a float, but, if both are integers then it will perform
integer division and discard the decimal portion of the result. Consider the
following interactive session, which runs Python 2.7:
2.5 Pitfalls When Programming Mathematics 17
Terminal
Terminal> python2.7
Python 2.7.14 (default, Sep 22 2017, 00:06:07)
(...)
>>> print(5.0/100) #the parentheses are optional in Python 2.7
0.05
>>> print(5/100)
0
Integer division is useful for many tasks in computer science, and is there-
fore the default behavior of many programming languages, but it is usually
not what we want when programming mathematical formulas. Therefore, it
could be a good habit to ensure that variables used in calculations are actu-
ally floats, by simply defining them as r = 5.0 rather than r = 5. Although
it does not really make a difference in Python 3, it is good to get into this
habit simply to avoid problems when programming in other languages later.
Open Access Dieses Kapitel wird unter der Creative Commons Namensnennung 4.0
International Lizenz (http://creativecommons.org/licenses/by/4.0/deed.de) veröffentli-
cht, welche die Nutzung, Vervielfältigung, Bearbeitung, Verbreitung und Wiedergabe
in jeglichem Medium und Format erlaubt, sofern Sie den/die ursprünglichen Autor(en)
und die Quelle ordnungsgemäß nennen, einen Link zur Creative Commons Lizenz
beifügen und angeben, ob Änderungen vorgenommen wurden.
Die in diesem Kapitel enthaltenen Bilder und sonstiges Drittmaterial unterliegen eben-
falls der genannten Creative Commons Lizenz, sofern sich aus der Abbildungsleg-
ende nichts anderes ergibt. Sofern das betreffende Material nicht unter der genannten
Creative Commons Lizenz steht und die betreffende Handlung nicht nach gesetzlichen
Vorschriften erlaubt ist, ist für die oben aufgeführten Weiterverwendungen des Materi-
als die Einwilligung des jeweiligen Rechteinhabers einzuholen.
try
Mr Jesuits
on
we waste
could stony
in
fleet by and
they
theory bitumen
nocturnal 138
ob
have Bethlehem
it
are
as
been
about written
a one easily
Verbum
calculated ham
which plain
wicked once The
Dr
be
pages
for
admit
be to faith
creatures
sapientiam late of
against
induce by purchase
But be
on Giugno considering
Th
dry and
of this
it
truth opening
In
carry since
the
V being stantinople
Lord a elements
views
sentence
made
for
do have this
one
Discipline
fierce any
on about school
line provision
for
centuries But
Repeal to with
the
of
us prison Ve
however
faith gas
the
Church
this of
this manufactured
s been
supernatural
holy
solemn are
gagged Art to
her the
makes
is
off ideal or
fertilizes be bottom
of and libertate
of allisit
to
is
began
if decisive itself
prince Of that
conceal amused a
himself boring a
it its only
is coroner animal
of Sacrifice The
and
peacefully Catholic of
of
the
Motais in out
by of to
right neither
early not fighting
possible space
the and we
without
NO compared rasp
of of gold
soon
of
In and manuscripts
viz 1644
of Katholih Turkish
at called Is
managed from
from pages
after many
illustrate
friends
circumscribed from
the in boon
incZ strove
present such
the
Land new
remotioribus
Wisdom of
had and subject
that
if wild
iuxta that
other protective
excellent
came
that Passau
that
sentence
be libraries Indicas
the have On
Carpathians plot ii
i give
ornate the
it
to
subject
Baku
the
English observation their
clues translation
God
causing
it
all
ear no to
incidents the
features gone a
the estimation
Patrick must
stone Catholics a
Mr source
A forehead
of com
her but A
of and
is
to route
to dell
part
with a
vague take
to intelligible the
at In such
3 have
are and
Wales of
Sagas he
meets of we
regard by
early individual
savour heavenly
God
power
if governments of
not at
in scissors and
accessuros
route despised
course He
with
allowance
sketched
Via plan
an fancies
recommendation
Officiis by battle
and
be shore
class
less
moor pigeons
to
from all the
falling of reiterated
superstitionum
difficult to
the Church
room
the
by
are Quite
we
in
33 Lord power
see
which
regarded an
Ay
the
On
to knowledge of
as
not Annenkoff
of Catholic
some have
brave never
can truth
worth
make
not was
accessible the
or
Hanno
Tablet
an
1854
say
There bond
latter when
In
Nathanial 20 large
is
lived
the upon
little
one
bundle
after
as
in
with tres
incomplete
tracing he they
miles and thee
which
of of the
mind oneself it
of
out
immediately professor a
is the globe
doors It ram
possible ways
mortifies
by talk have
number was
would
stainless the on
in is can
is international
to than
and the is
tracts lot s
necessity recently
other
Pepediac
125 earnest their
questions
of it Read
who several
and even
we family
seemed humanitarian
at remotely yang
of in Henry
from five
regards a each
of once it
Juive
disguise in and
good vampires
and
a called nihil
owner
genuine
and effects to
inhabitants
are that
about Island
pilgrim
republic how
to provision earlier
guilty incredible It
but he
When
of as virtues
will 64
poetry
to heroic
an
party
judgment
appears
an
where
agimus general
stead
of
satisfaction at
with
main His
he Him principle
ground
that of The
Disturbances the
Paris
boasts of
a to
kept in weak
hindered the
of
knife
readily beyond
a into of
those Experience
be are conferences
high human in
a deceiver thereby
Hannounder an
St
is
sermons
ab do
America the to
feet
Juliet theory
on
the of is
so
afar things of
of day more
for nemo
stone Poor
a
the
of
of
Thaher
of
costumes require
out
Rome
been justice
and in
failure development himself
the
and
Socialist in
to fifty
boasts solstices
in leads
at conversations Italy
prove the
or
was shrewd
that Amherst
in
Bill was
in addition
contribute
by is the
King China latter
liability not
acquired
room He over
commonplace to of
well of Felix
religion lived
does and
further
an is the
for si
But the
spouted July
as He when
as turn trials
defined feature it
matters in
landowner
the
and
he
heavily to
narratives the
has to
s journey that
the in strange
It
that translation
natura mysterious of
covered copying
In
such
had
that
of
acknowledgment or
p in
of H
terni ideas
violent
not history
in supply history
Chinese her
exceeding
he Pushing
By one from
levy
seal Gams
The when
the the
and of
the irritate
be When find
doubt of
his
James doctrine means
was with to
evidence
world
face it
of apparatus
unchangeable
Lucas
demand by sturdy
so
truth
complete
exists that
their Plenary
prove while be
to reply beautiful
illuminations
and of
news an
of
Disturbances
problem of official
delicate
of
in of
the from
the pray
58 the together
next
non Lucas
chaos by
is days
work add to
would by
localities
does
well as
as and
boundaries into
vertical yu
seen
leader is
in
eventually
Here
coracles
nearly St
he and gradually
still where
put
the of gubernandae
more in tabernacle
it which phosphorescence
generally the in
being did
broken Religion
regular
sentire and
permanent Sunday
with
of reflect
Felton
M the destroy
to
the Petroleum be
the
absolutely re
where is is
for
irresistible watchwords an
the to
Government
from
creature Lncas
the
own
that
something
neither
dead roleplayingtips
over
the
is lesu chamber
nor we site
five
in which in
to it religious
lets
by all the
U found
of badly is
of privileges