100% found this document useful (3 votes)
28 views

Introduction to Scientific Programming with Python Joakim Sundnes instant download

The document provides information about the book 'Introduction to Scientific Programming with Python' by Joakim Sundnes, which is part of the Simula SpringerBriefs on Computing series. It aims to offer a compact introduction to scientific programming, primarily targeting students in mathematics and natural sciences, and is designed to supplement existing literature on the subject. The book is open access, allowing for broader dissemination of knowledge and includes practical programming examples and exercises.

Uploaded by

gareypocank9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
28 views

Introduction to Scientific Programming with Python Joakim Sundnes instant download

The document provides information about the book 'Introduction to Scientific Programming with Python' by Joakim Sundnes, which is part of the Simula SpringerBriefs on Computing series. It aims to offer a compact introduction to scientific programming, primarily targeting students in mathematics and natural sciences, and is designed to supplement existing literature on the subject. The book is open access, allowing for broader dissemination of knowledge and includes practical programming examples and exercises.

Uploaded by

gareypocank9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Introduction to Scientific Programming with

Python Joakim Sundnes pdf download

https://textbookfull.com/product/introduction-to-scientific-
programming-with-python-joakim-sundnes/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Learning Scientific Programming with Python 1st Edition


Christian Hill

https://textbookfull.com/product/learning-scientific-programming-
with-python-1st-edition-christian-hill/

Learning Scientific Programming With Python 2nd Edition


Christian Hill

https://textbookfull.com/product/learning-scientific-programming-
with-python-2nd-edition-christian-hill/

Learning Scientific Programming with Python 2nd Edition


Christian Hill

https://textbookfull.com/product/learning-scientific-programming-
with-python-2nd-edition-christian-hill-2/

Programming For Computations - Python: A Gentle


Introduction To Numerical Simulations With Python 3.6
Svein Linge

https://textbookfull.com/product/programming-for-computations-
python-a-gentle-introduction-to-numerical-simulations-with-
python-3-6-svein-linge/
Introduction to Computation and Programming Using
Python with Application to Understanding Data Guttag

https://textbookfull.com/product/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-
guttag/

Introduction to GIS Programming and Fundamentals with


Python and ArcGIS 1st Edition Chaowei Yang

https://textbookfull.com/product/introduction-to-gis-programming-
and-fundamentals-with-python-and-arcgis-1st-edition-chaowei-yang/

Bite Size Python An Introduction to Python Programming


1st Edition April Speight

https://textbookfull.com/product/bite-size-python-an-
introduction-to-python-programming-1st-edition-april-speight/

Introduction to Programming with Fortran Chivers

https://textbookfull.com/product/introduction-to-programming-
with-fortran-chivers/

Introduction to Computation and Programming Using


Python With Application to Understanding Data Second
Edition John V. Guttag

https://textbookfull.com/product/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-
second-edition-john-v-guttag/
SIMULA SPRINGER BRIEFS ON COMPUTING 006

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.

More information about this series at http://www.springer.com/series/13548


Joakim Sundnes

Introduction
to Scientific
Programming
with Python
Joakim Sundnes
Simula Research Laboratory
Lysaker, Norway

Simula SpringerBriefs on Computing


ISBN 978-3-030-50355-0 ISBN 978-3-030-50356-7 (eBook)
https://doi.org/10.1007/978-3-030-50356-7

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.

January 2016 Prof. Aslak Tveito


CEO
Dr. Martin Peters
Executive Editor Mathematics
Springer Heidelberg, Germany

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.

May 2020 Joakim Sundnes


Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

1 Getting Started with Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


1.1 The First Example: Hello, World! . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Different Ways to Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Computing with Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5


2.1 Programming Simple Mathematics . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Variables and Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Formatting Text Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.4 Importing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.5 Pitfalls When Programming Mathematics . . . . . . . . . . . . . . . . . 15

3 Loops and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19


3.1 Loops for Automating Repetitive Tasks . . . . . . . . . . . . . . . . . . . 19
3.2 Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3 Using Lists to Store Sequences of Data . . . . . . . . . . . . . . . . . . . . 23
3.4 Iterating Over a List with a for Loop . . . . . . . . . . . . . . . . . . . . . 25
3.5 Nested Lists and List Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.6 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

4 Functions and Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


4.1 Programming with Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2 Function Arguments and Local Variables . . . . . . . . . . . . . . . . . . 38
4.3 Default Arguments and Doc Strings . . . . . . . . . . . . . . . . . . . . . . 44
4.4 If-Tests for Branching the Program Flow . . . . . . . . . . . . . . . . . . 46
4.5 Functions as Arguments to Functions . . . . . . . . . . . . . . . . . . . . . 48
4.6 Solving Equations with Python Functions . . . . . . . . . . . . . . . . . 50
4.7 Writing Test Functions to Verify our Programs . . . . . . . . . . . . . 53

xiii
xiv Contents

5 User Input and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 57


5.1 Reading User Input Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.2 Flexible User Input with eval and exec . . . . . . . . . . . . . . . . . . 61
5.3 Reading Data from Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.4 Writing Data to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.5 Handling Errors in Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.6 Making Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

6 Arrays and Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81


6.1 NumPy and Array Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.2 Plotting Curves with Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.3 Plotting Discontinuous and Piecewise-Defined Functions . . . . . 90
6.4 Making a Movie of a Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.5 More Useful Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

7 Dictionaries and Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101


7.1 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.2 Example: A Dictionary for Polynomials . . . . . . . . . . . . . . . . . . . 105
7.3 Example: Reading File Data to a Dictionary . . . . . . . . . . . . . . . 107
7.4 String Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

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

9 Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135


9.1 Class Hierarchies and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . 135
9.2 Example: Classes for Numerical Differentiation . . . . . . . . . . . . . 139
9.3 Example: Classes for Numerical Integration . . . . . . . . . . . . . . . . 142

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.

1.1 The First Example: Hello, World!


Most introductory books on programming start with a so-called Hello, World!
program, which is a program that simply writes Hello, World! to the screen.
In Python, this program is just a single line;
print("Hello, World!")

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.

1.2 Different Ways to Use Python


As briefly mentioned above, Python offers some alternatives to the traditional
style of programming using a text editor and a terminal window, and some of
these alternatives can be very useful when learning to program. For instance,
we can use Python interactively by simply typing python or ipython in a
terminal window, without a subsequent file name. This will open an environ-
ment for typing and running Python commands, which is not very suitable for
writing programs over several lines, but extremely useful for testing Python
commands and statements, or simply using Python as a calculator. In a reg-
ular terminal window on macOS or Linux, an interactive version of the Hello,
World! example would look something like
Terminal

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 [1]: print("Hello, World!")


Hello, World!

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

A third way to use Python is through Jupyter notebooks, which are a


form of interactive notebooks that combine code and text. The notebooks
are viewed through a browser and look quite similar to a simple web page,
but with the important difference that the code segments are "live" Python
code that can be run, changed, and re-run while reading the document. These
features are particularly useful for teaching purposes, since detailed explana-
tions of new concepts are easily combined with interactive examples. All the
chapters of this book are also available as Jupyter notebooks.
Minor drawbacks of the Python language. Although Python is a very
popular and suitable language for learning to program, it also has some minor
drawbacks. One of the more important is tightly linked to its advantage of
being a flexible high-level language with a short and intuitive syntax. Writing
small programs in Python can be very efficient, and beginners can quickly
start writing useful programs, but the downside is that the code can become
messy as the programs grow in size and complexity. Other languages such as
C, C++, and Java tend, to enforce more structure in the code, which can
be confusing for beginners and annoying when you want to write a small
program quickly, but it can be more efficient in the long run when writing
larger programs. However, it is certainly possible to write neat and nicely
structured programs in Python as well, but this requires a choice by the
programmer to follow certain principles of coding style, and is not enforced
by the language itself.
Another slightly annoying aspect of Python is that it exists in different
versions. At the time of this writing, Python 3 has been dominant for quite
a while, but if you look for programming resources online or read older text-
books, you will find many examples using Python 2. For the mathematics-
centered programming covered in this book, the difference between Python
2 and Python 3 is actually quite small, but some differences are important
to be aware of. The most obvious one is how print works. In Python 2,
the program above would read print "Hello, World!", that is, without
the parentheses. Since nearly all code examples use print to some extent,
programs written in Python 2 will typically not run in Python 3. One partic-
ularly relevant resource for scientific Python (on which this book is largely
based) is "A Primer on Scientific Programming with Python", by Hans Petter
Langtangen3 . However, the latest version of that book was written in 2016,
and all the code examples are in Python 2 and will stop with an error mes-
sage if they are run in Python 3. In most cases, the only error is the missing
parentheses; so the addition of parentheses to all the print statements will
make most of the examples run fine in Python 3. We will comment on some
of the other differences between the Python versions later.

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.

2.1 Programming Simple Mathematics

To introduce the concepts of this chapter, we first consider a simple formula


for calculating the interest on a bank deposit:

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

© The Author(s) 2020


J. Sundnes, Introduction to Scientific Programming with 5
Python, Simula SpringerBriefs on Computing 6,
https://doi.org/10.1007/978-3-030-50356-7_2
6 2 Computing with Formulas

interest0.py in a regular terminal or run interest0.py in an iPython


window or Spyder.
The interest0.py program is not much more complex or useful than the
Hello, World! example from the previous chapter, but there are a couple of
important differences. First, notice that, in this case we did not use quotation
marks inside the parentheses. This is because we want Python to evaluate
the mathematical formula, and print the result to the screen, which works
fine as long as the text inside the parentheses is valid Python code, or, more
precisely, a valid expression that can be evaluated to produce a result. If we
put quotation marks around the formula above, the code would still work,
but the result is not what we want – try it!. At this point, it is also worth
noting that, while we stated above that Python is a flexible and high-level
language, all programming languages are extremely picky about spelling and
grammar. Consider, for instance the line
write(100*(1+5,0/100)^7)

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

use whitespace in order to make the code as readable as possible to humans,


since Python will ignore it anyway.

2.2 Variables and Variable Types

We are used to variables in mathematics, such as P , r and n in the interest


formula above. We can use variables in a program too, and this makes the
program easier to read and understand:
primary = 100
r = 5.0
n = 7
amount = primary * (1+r/100)**n
print(amount)

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

for instance, a is different from A. The following program is identical to the


one above, but with different variable names:
initial_amount = 100
interest_rate = 5.0
number_of_years = 7
final_amount = initial_amount*(1 + interest_rate/100)**number_of_years
print(final_amount)

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

The line t = t + 0.1 would not make sense as a mathematical equation,


but it is a perfectly valid assignment in a computer program. The right-hand
side is evaluated first, using the value of t already defined, and then the t
variable is updated to hold the result of the calculation. The equality sign
in Python is called the assignment operator, and, although it works similarly
to an equality sign in mathematics, it is not quite the same. If we want the
more usual meaning of the equality sign, for instance, to determine if two
numbers are equal, the operator to use in Python is ==. A trivial comparison
could look like
a = 5
print(a == 5)

True

We will see many more such examples later.


2.2 Variables and Variable Types 9

Comments are useful for explaining the thought process in pro-


grams. It is possible to combine the strengths of the two programs above
and have both compact variable names and a more detailed description of
what each variable means. This can be done using comments, as illustrated
in the following example:
# program for computing the growth of
# money deposited in a bank
primary = 100 # initial amount
r = 5.0 # interest rate in %
n = 7 # the number of years
amount = primary * (1+r/100)**n
print(amount)

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)

Strings that contain numbers are a potential source of confusion. Consider


for instance the code
x1 = 2
x2 = "2"
print(x1+x1)
print(x2+x2)

4
22

We see that the variable x2 is treated as a text string in Python, because


it was defined using the quotation marks, even though it contains a single
number. For the examples we have seen so far, it is easy to ensure that
numbers are numbers, simply by not using quotation marks when they are
defined. However, later in this book, we will write programs that read data
from files or user input. Such data will usually be in the form of text, and any
numbers will be text strings similar to the variable x2 above. Before using
the numbers in calculations, we therefore need to convert them to actual
numbers, which can be done with the built-in function float:
x1 = float(x1)
x2 = float(x2)
print(type(x1))
print(type(x2))
print(x2+x2)
2.3 Formatting Text Output 11

<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.

2.3 Formatting Text Output

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.")

After 7 years, 100 EUR has grown to 140.71004226562505 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}.")

Default output gives t = 1.234567.


We can set the precision: t = 1.2.
Or control the number of decimals: t = 1.23.

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}.")

We may set the space used for the output: t = 1.23

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}")

Integer set to occupy exactly 8 chars of space: r = 87

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}.")

Without the format specifier: a = 786345687.12, b = 1.2345.


With the format specifier: a = 7.86346e+08, b = 1.2345.

2.4 Importing Modules


We have seen that standard arithmetic operations are directly available in
Python, with no extra effort. However, what if more advanced mathematical
operations, such as sin x, cos x, ln x, are required? These functions are not
available directly, but can be found in a so-called module, which must be
imported before they can be used in our program. Generally, a great deal of
functionality in Python is found in such modules, and we will import one or
more modules in nearly all the programs we write. Standard mathematical
functions are found in a module named math, and the following code computes
the square root of a number using the sqrt function in the math module:
import math
r = math.sqrt(2)
# or
from math import sqrt
r = sqrt(2)
# or
from math import * # import everything in math
r = sqrt(2)

This example illustrate three different ways of importing modules. In the


first one, we import everything from the math module, but everything we
want to use must be prefixed with math. The second option imports only
the sqrt function, and this function is imported into the main namespace of
the program, which means it can be used without a prefix. Finally, the third
option imports everything from math into the main namespace, so that all
the functions from the module are available in our program without a prefix.
14 2 Computing with Formulas

A natural question to ask is why we need three different ways to import a


module. Why not use the simple from math import * and gain access to all
the mathematics functions we need? The reason is that we will often import
from several modules in the same program, and some of these modules can
contain functions with identical names. In these cases it is useful to have some
control over which functions are actually used, either by selecting only what
we need from each module, as in from math import sqrt, or by importing
with import math so that all the functions must be prefixed with the module
name. To avoid confusion later, it might be good to get into the habit of
importing modules in this manner right away, although, in small programs
where we import only a single module, there is nothing wrong with from
math import *.
As another example of computing with functions from math, consider eval-
uating the bell-shaped Gaussian function
  2 
1 1 x−m
f (x) = √ exp −
2πs 2 s

for m = 0, s = 2, and x = 1. For this calculation, we need to import the square


root, the exponential function, and π from the math module, and the Python
code may look as follows:
from math import sqrt, pi, exp
m = 0
s = 2
x = 1.0
f = 1/(sqrt(2*pi)*s) * exp(-0.5*((x-m)/s)**2)
print(f)
Notice that for this more complex formula it is very easy to make mistakes
with the parentheses. Such errors will often lead to an error message that
points to a syntax error on the next line of your program. This can be con-
fusing at first, so it is useful to be aware of. If you obtain an error message
pointing to a line directly below a complex mathematical formula, the source
is usually a missing closing parenthesis in the formula itself.
Finding information about Python modules. At this point, it is nat-
ural to ask how we know where to find the functions we want. Say we
need to compute with complex numbers. How can we know if there is a
module in Python for this? And, if so, what is it called? Generally, learn-
ing about the useful modules and what they contain are part of learning
Python programming, but knowing where to find such information could be
even more important. An excellent source is the Python Library Reference
(https://docs.python.org/3/library/), which contains information about all
the standard modules that are distributed with Python. More generally, a
Google search for complex numbers python quickly leads us to the cmath
module, which contains mostly the same functions as math, but with support
for complex numbers. If we know the name of a module and want to check its
2.5 Pitfalls When Programming Mathematics 15

contents, we can go to straight to the Python Library Reference, but there


are also other options. The command pydoc in the terminal window can be
used to list information about a module (try, e.g., pydoc math), or we can
import the module in a Python program and list its contents with the built-in
function dir.
import math
print(dir(math))

[’__doc__’, ’__file__’, ’__loader__’, ’__name__’, (...) ]

2.5 Pitfalls When Programming Mathematics


Usually, the mathematical operations described above work as expected.
When the results are not as expected, the cause is usually a trivial error
introduced during typing, typically assigning the wrong value to a variable
or mismatching the number of parentheses. However, some potential error
sources are less obvious and are worth knowing about, even if they are rela-
tively rare.
Round-off errors give inexact results. Computers have inexact arith-
metic because of rounding errors. This is usually not a problem in computa-
tions, but in some cases it can cause unexpected results. Let us, for instance,
compute 1/49 · 49 and 1/51 · 51:
v1 = 1/49.0*49
v2 = 1/51.0*51
print(f"{v1:.16f} {v2:.16f}")

The output with 16 decimal places becomes


0.9999999999999999 1.0000000000000000

Most real numbers are represented inexactly on a computer, typically with


an accuracy of 17 digits. Neither 1/49 nor 1/51 are represented exactly, and
the error is approximately 10−16 . Errors of this order usually do not matter,
but there are two particular cases in which they can be significant. In one
case, errors can accumulate through numerous computations, ending up as a
significant error in the final result. In the other case, which is more likely to
be encountered in the examples of this book, the comparison of two decimal
numbers can be unpredictable. The two numbers v1 and v2 above are both
supposed to be equal to one, but look at the result of this code:
print(v1 == 1)
print(v2 == 1)
16 2 Computing with Formulas

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.
Another Random Document on
Scribd Without Any Related Topics
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like