Learning Scientific Programming with Python Hill download
Learning Scientific Programming with Python Hill download
pdf download
https://ebookmass.com/product/learning-scientific-programming-
with-python-hill/
https://ebookmass.com/product/learning-scientific-programming-with-
python-2nd-edition-christian-hill-2/
https://ebookmass.com/product/learning-scientific-programming-with-
python-2nd-edition-christian-hill/
https://ebookmass.com/product/mastering-functional-programming-with-
python-brett-neutreon/
https://ebookmass.com/product/programming-and-problem-solving-with-
python-ashok-namdev-kamthane/
Python Programming and SQL: 10 Books in 1 - Supercharge
Your Career with Python Programming and SQL Andrew Reed
https://ebookmass.com/product/python-programming-and-sql-10-books-
in-1-supercharge-your-career-with-python-programming-and-sql-andrew-
reed/
https://ebookmass.com/product/learning-java-beginning-programming-
with-java-for-dummies-bach/
https://ebookmass.com/product/beginning-programming-with-python-for-
dummies-3rd-edition-john-paul-mueller/
https://ebookmass.com/product/machine-learning-for-time-series-
forecasting-with-python-francesca-lazzeri/
https://ebookmass.com/product/programming-the-raspberry-pi-third-
edition-getting-started-with-python-simon-monk/
Learning Scientific Programming with Python
Learn to master basic programming tasks from scratch with real-life, scientifically
relevant examples and solutions drawn from both science and engineering. Students and
researchers at all levels are increasingly turning to the powerful Python programming
language as an alternative to commercial packages and this fast-paced introduction
moves from the basics to advanced concepts in one complete volume, enabling readers
to quickly gain proficiency.
Beginning with general programming concepts such as loops and functions within
the core Python 3 language, and moving on to the NumPy, SciPy and Matplotlib
libraries for numerical programming and data visualization, this textbook also discusses
the use of IPython Notebooks to build rich-media, shareable documents for scientific
analysis. Including a final chapter introducing challenging topics such as floating-
point precision and algorithm stability, and with extensive online resources to support
advanced study, this textbook represents a targeted package for students requiring a
solid foundation in Python programming.
Christian Hill is a physicist and physical chemist at University College London and
Oxford University. He has over twenty years’ experience of programming in the phys-
ical sciences and has been programming in Python for ten years. His research uses
Python to produce, analyse, process, curate and visualize large data sets for the predic-
tion of the properties of planetary atmospheres.
Learning Scientific Programming
with Python
Christian Hill
University College London and
Somerville College, University of Oxford
University Printing House, Cambridge CB2 8BS, United Kingdom
www.cambridge.org
Information on this title: www.cambridge.org/9781107075412
© Cambridge University Press 2015
This publication is in copyright. Subject to statutory exception
and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without
the written permission of Cambridge University Press.
First published 2015
Printed in the United Kingdom by TJ International Ltd. Padstow Cornwall
A catalogue record for this publication is available from the British Library
Library of Congress Cataloguing in Publication data
Hill, Christian, 1974–
Learning scientific programming with Python / Christian Hill,
University College London and Somerville College, University of Oxford.
pages cm
ISBN 978-1-107-07541-2 (Hardback) – ISBN 978-1-107-42822-5 (Paperback)
1. Science–Data processing. 2. Science–Mathematics.
3. Python (Computer program language) I. Title.
Q183.9.H58 2015
005.13 3–dc23 2015017085
ISBN 978-1-107-07541-2 Hardback
ISBN 978-1-107-42822-5 Paperback
Additional resources for this publication at www.cambridge.org/9781107075412
Cambridge University Press has no responsibility for the persistence or accuracy of
URLs for external or third-party internet websites referred to in this publication,
and does not guarantee that any content on such websites is, or will remain,
accurate or appropriate.
Contents
1 Introduction 1
1.1 About this book 1
1.2 About Python 2
1.3 Installing Python 5
1.4 The command line 6
v
vi Contents
6 NumPy 184
6.1 Basic array methods 184
6.2 Reading and writing an array to a file 216
6.3 Statistical methods 225
6.4 Polynomials 232
6.5 Linear algebra 247
6.6 Matrices 256
6.7 Random sampling 262
6.8 Discrete Fourier transforms 272
7 Matplotlib 280
7.1 Matplotlib basics 280
7.2 Contour plots, heatmaps and 3D plots 317
8 SciPy 333
8.1 Physical constants and special functions 333
8.2 Integration and ordinary differential equations 355
8.3 Interpolation 374
8.4 Optimization, data-fitting and root-finding 380
Many people have helped directly or indirectly in the preparation of this book. Thanks
are due especially to Jonathan Tennyson at UCL, and Laurence Rothman and Iouli Gor-
don for hosting my sabbatical year at the Harvard-Smithsonian Center for Astrophysics.
As ever, I owe much to Natalie Haynes for her constant support, encouragement and
friendship.
vii
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
1 Introduction
This book is intended to help scientists and engineers learn version 3 of the Python
programming language and its associated NumPy, SciPy and Matplotlib libraries. No
prior programming experience or scientific knowledge in any particular field is assumed.
However, familiarity with some mathematical concepts such as trigonometry, complex
numbers and basic calculus is helpful to follow the examples and exercises.
Python is a powerful language with many advanced features and libraries; while the
basic syntax of the language is straightforward to learn, it would be impossible to teach
it in depth in a book of this size. Therefore, we aim for a balanced, broad introduction to
the central features of the language and its important libraries. The text is interspersed
with examples relevant to scientific research, and at the end of most sections there are
questions (short problems designed to test knowledge) and exercises (longer problems
that usually require a short computer program to solve). Although it is not necessary
to complete all of the exercises, readers will find it useful to attempt at least some of
them. Where a section, example or exercise contains more advanced material that may
be skipped on first reading, this is indicated with the symbol ♦.
In Chapter 2 of this book, the basic syntax, data structures and flow control of a
Python program are introduced. Chapter 3 is a short interlude on the use of the Pylab
library for making graphical plots of data: this is useful to visualize the output of
programs in subsequent chapters. Chapter 4 provides more advanced coverage of the
core Python language and a brief introduction to object-oriented programming. There
follows another short chapter introducing the popular IPython and IPython Notebook
environments, before chapters on scientific programming with NumPy, Matplotlib and
SciPy. The final chapter covers more general topics in scientific programming, including
floating point arithmetic, algorithm stability and programming style.
Readers who are already familiar with the Python programming language may wish
to skim Chapters 2 and 4.
Code examples and exercise solutions may be downloaded from the book’s website at
scipython.com . Note that while comments have been included in these downloadable
programs, they are not so extensive in the printed version of this book: instead, the code
is explained in the text itself through numbered annotations (such as ➊). Readers typing
in these programs for themselves may wish to add their own explanatory comments to
the code.
1
2 Introduction
Output:
Isaac Newton
Marie Curie
Albert Einstein
int main()
{
int i;
char names[NUMBER_OF_STRINGS][MAX_STRING_LENGTH+1];
strcpy(names[0], "Isaac Newton");
strcpy(names[1], "Marie Curie");
strcpy(names[2], "Albert Einstein");
for (i=0;i<NUMBER_OF_STRINGS;i++) {
fprintf(stdout, "%s\n", names[i]);
}
return EXIT_SUCCESS;
}
Even if you are not familiar with the C language, you can see there is quite a lot of
overhead involved in coding even this simple task in C: three includes of libraries not
loaded by default, explicit declarations of variables to hold the list (“array”, in C) of
names, names, and a counter, i, and explicit indexing of this array in a for loop; you
even need to add the line endings (‘\n’ is the “new line” character). This source code
then has to be compiled – converted into the machine code that the computer processor
understands – before it can be run (executed). Furthermore, there is plenty of scope for
errors (bugs): trying to print the name stored in name[10] will likely cause junk to be
output: the C compiler won’t stop you from accessing this nonexistent name.
The same program written in three lines of Python is clean and expressive: we do
not have to explicitly declare that names is a list of strings, there is no need for a
loop counter like i and there are no separate libraries to include (import in Python).
To run the Python program, one simply needs to type python eg1-names.py which
will automatically invoke the Python “interpreter” to compile and then run the resulting
“byte-code” (a kind of intermediate representation of the program between its source
and the ultimate machine code that Python dispatches to the processor).
Python’s syntax aims to ensure that “There should be one – and preferably only one –
obvious way to do it.” This differs from some other popular high-level languages such as
Ruby and Perl, which take the opposite approach, encapsulated by the mantra “there’s
more than one way to do it.” For example, there are (at least) four obvious ways to
output the same list in Perl:2
Listing 1.3 Different ways to output a list of names using a program written in Perl
@names = ("Isaac Newton", "Marie Curie", "Albert Einstein");
# Method 1
print "$_\n" for @names;
# Method 2
print join "\n", @names;
print "\n";
# Method 3
print map { "$_\n" } @names;
# Method 4
$" = "\n";
print "@names\n";
• Its clean and simple syntax makes writing Python programs fast and generally
minimizes opportunities for bugs to creep in. When done right, the result is high-
quality software that is easy to maintain and extend.
• It’s free – Python and its associated libraries are free of cost and open source,
unlike commercial offerings such as Mathematica.
• Cross-platform support: Python is available for every commonly available
computer system, including Windows, Unix, Linux and Mac OS X. Although
platform-specific extensions exist, it is possible to write code that will run on any
platform without modification.
• Python has a large library of modules and packages that extend its functionality.
Many of these are available as part of the “standard library” provided with the
Python interpreter itself. Others, including the NumPy, SciPy and Matplotlib
libraries used in scientific computing, can be downloaded separately for no cost.
• Python is relatively easy to learn. The syntax and idioms used for basic operations
are applied consistently in more advanced usage of the language. Error messages
are generally meaningful assessments of what went wrong rather than the generic
“crashes” that can occur in compiled lower-level languages such as C.
• Python is flexible: it is often described as a “multi-paradigm” language that
contains the best features from the procedural, object-oriented and functional
programming paradigms. There is little need for the work-arounds required in
some languages when a problem can only be solved cleanly with one of these
approaches.
So where’s the catch? Well, Python does have some disadvantages and isn’t suitable
for every application.
• The speed of execution of a Python program is not as fast as some other, fully
compiled languages such as C and Fortran. For heavily numerical work, the
NumPy and SciPy libraries alleviate this to some extent by using compiled-
C code “under the hood,” but at the expense of some reduced flexibility. For
many, many applications, however, the speed difference is not noticeable and the
reduced speed of execution more than offset by a much faster speed of develop-
ment. That is, it takes much less time to write and debug a Python program than
to do the same in C, C++ or Java.
• It is hard to hide or obfuscate the source code of a Python program to prevent
others from copying or modifying it. However, this doesn’t mean that successful
commercial Python programs don’t exist.
• A common complaint about Python has historically been that its rapid devel-
opment has led to compatibility issues between versions. Certainly there are
important differences between Python 2 and Python 3 (described in the next
section), but the complaint stems from the fact that within the Python 2 series,
there were major improvements and additions to the language that meant that
code written in a later version (say, 2.7) would not run on an earlier version of
Python (e.g., 2.6), although code written for an earlier version of Python will
always run on a later version (within the same branch, 2 or 3). If you use the
1.3 Installing Python 5
latest version of Python (see Section 1.3) you probably won’t run into a problem,
but some operating systems that come with Python are rather conservative and
install by default only an older version.
The official website of Python is www.python.org/, and contains full and easy-to-follow
instructions for downloading Python. However, there are several full distributions which
include the NumPy, SciPy and Matplotlib libraries (the “SciPy stack”) to save you from
having to download and install these yourself:
• Anaconda is available for free (including for commerical use) from http://
continuum.io/downloads. It installs both Python 2 and Python 3, but the default
version can be selected either before downloading as indicated on this web page,
or subsequently using the ‘conda’ command.
• Enthought Canopy is a similar distribution with a free version and various tiers
of paid-for versions including technical support and development software.
In most cases, one of these distributions should be all you need. We provide some
platform-specific notes below.
The source code (and binaries for some platforms) for the NumPy, SciPy, Matplotlib
and IPython packages are available separately at:
6 Introduction
• NumPy: http://sourceforge.net/projects/numpy/
• SciPy: http://sourceforge.net/projects/scipy/
• Matplotlib: http://matplotlib.org/downloads.html
• IPython: https://github.com/ipython/ipython/releases
Windows
Windows users have a couple of further options for installing the full SciPy stack:
Python(x,y) (https://code.google.com/p/pythonxy/) and WinPython (http://winpython
.sourceforge.net/). Both are free.
Mac OS X
Mac OS X, being based on Unix, comes with Python, but it is usually an older version
of Python 2. You must not delete or modify this installation (it’s needed by the operating
system), but you can follow the instructions above for obtaining Python 3 and the SciPy
stack. OS X does not have a native package manager (an application for managing
and installing software), but the two popular third-party package managers, Homebrew
(http://brew.sh/) and MacPorts (www.macports.org/), can both supply Python 3 and its
packages if you prefer this option.
Linux
Almost all Linux distributions come with Python 2, but usually not Python 3, so you
will need to install it from the links above: the Anaconda and Canopy distributions
both have versions for Linux. Most Linux distributions come with their own software
package managers (e.g., apt in Debian and rpm for RedHat). These can be used to
install Python 3 and its libraries, though finding the necessary package repositories may
take some research on the Internet. Be careful not to replace or modify your system
installation as other applications may depend on it.
Most of the code examples in this book are written as standalone programs which can
be run from the command line (or from within an integrated development environment
(IDE) if you use one: see Section 9.3.2). To access the command line interface (also
known as a console or terminal) on different platforms, follow the instructions below.
• Windows 7 and earlier: Start > All Programs > Command Prompt; alternatively,
type cmd in the Start > Run input box.
• Windows 8: Preview (lower left of screen) > Windows System: All apps; alterna-
tively type ‘cmd’ in the search box pulled down the top-right corner of the screen.
• Mac OS X: Finder > Applications > Utilities > Terminal
• Linux: if you are not using a graphical interface you are already at the command
line; if you are, then locate the Terminal application (distributions vary, but it is
usually found within a System Utilities or System Tools subfolder).
1.4 The command line 7
Commands typed at the command line are interpreted by an application called a shell,
which allows the user to navigate the file system and is able to start other applications.
For example, the command
python myprog.py
instructs the shell to invoke the Python interpreter, sending it the file myprog.py as
the script to execute. Output from the program is then returned to the shell and displayed
in your console.
2 The core Python language I
This chapter introduces the syntax, structure and data types of the Python program-
ming language. The first few sections do not involve writing much beyond a few
statements of Python code and so can be followed using the Python shell. This
is an interactive environment: the user enters Python statements that are executed
immediately after the Enter key is pressed.
The steps for accessing the “native” Python shell differ by operating system. To start
it from the command line, first open a terminal using the instructions from Section 1.4
and type python.
To exit the Python shell, type exit().
When you start the Python shell, you will be greeted by a message (which will vary
depending on your operating system and precise Python version). On my system, the
message reads:
Python 3.3.5 |Anaconda 2.0.1 (x86\_64)| (default, Mar 10 2014, 11:22:25)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
The three chevrons (>>>) are the prompt, which is where you will enter your Python
commands. Note that this book is concerned with Python 3, so you should check that
the Python version number reported on the first line is Python 3.X.Y where the precise
values of the minor version numbers X and Y should not be important.
Many Python distributions come with a slightly more advanced shell called IDLE,
which features tab-completion, and syntax highlighting (Python keywords are colored
specially when you type them). We will pass over the use of this application in favor of
the newer and more advanced IPython environment, discussed in Chapter 5.
It is also possible for many installations (especially on Windows) to start a Python
shell directly from an application installed when you install the Python interpreter itself.
Some installations even add a shortcut icon to your Desktop which will open a Python
shell when you click on it.
8
2.2 Numbers, variables, comparisons and logic 9
Integers
Integers are whole numbers such as 1, 8, −72 and 3847298893721407. In Python 3,
there is no limit to their magnitude (apart from the availability of your computer’s
memory).1 Integer arithmetic is exact.
Complex numbers
Complex numbers such as 4+3j consist of a real and an imaginary part (denoted by j in
Python), each of which is itself represented as a floating point number (even if specified
without a period). Complex number arithmetic is therefore not exact but subject to the
same finite precision considerations as floats.
A complex number may be specified either by “adding” a real number to an imaginary
one (denoted by the j suffix), as in 2.3 + 1.2j or by separating the real and imaginary
parts in a call to complex, as in complex(2.3, 1.2).
1 In Python 2, there were two kinds of integer: “simple” integers (system-dependent, but usually stored in
either 32 or 64 bits and “long” integers (of any size), indicated with the suffix L.
2 This corresponds to the implementation of the IEEE 754 double-precision standard.
10 The core Python language I
Example E2.1 Typing a number at the Python shell prompt simply echoes the number
back to you:
>>> 5
5
>>> 5.
5.0
>>> 0.10
➊ 0.1
>>> 0.0001
0.0001
>>> 0.0000999
➋ 9.99e-05
Note that the Python interpreter displays numbers in a standard way. For example:
➊ The internal representation of 0.1 discussed earlier is rounded to ‘0.1’, which is the
shortest number with this representation.
➋ Numbers smaller in magnitude than 0.0001 are displayed in scientific notation.
A number of one type can be created from a number of another type with the relevant
constructor:
>>> float(5)
5.0
>>> int(5.2)
5
>>> int(5.9)
➊ 5
>>> complex(3.)
➋ (3+0j)
➌ >>> complex(0., 3.)
3j
➊ Note that a floating point number is rounded down in casting it into an integer.
➋ Constructing a complex object from a float generates a complex number with the
imaginary part equal to zero.
➌ To generate a pure imaginary number, you have to explicitly pass two numbers to
complex with the first, real part, equal to zero.
*****
*****
*****
*****
*****
ebookmasss.com