Python_frontmatter
Python_frontmatter
Learn to master basic programming tasks from scratch with real-life, scientifically rel-
evant 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 gain proficiency quickly.
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 Jupyter Notebooks to build rich-media, shareable documents for scientific
analysis. The second edition features a new chapter on data analysis with the pandas
library and comprehensive updates, new exercises and examples. A final chapter
introduces more advanced topics such as floating-point precision and algorithm stability,
and extensive online resources support further study. This textbook represents a targeted
package for students requiring a solid foundation in Python programming.
Christian Hill is a physicist and physical chemist currently working at the Interna-
tional Atomic Energy Agency. He has over 25 years’ experience of programming in the
physical sciences and has been programming in Python for 15 years. His research uses
Python to produce, analyze, process, curate and visualize large data sets in the area of
spectroscopy, plasma physics and material science.
CHRISTIAN HILL
www.cambridge.org
Information on this title: www.cambridge.org/9781108745918
DOI: 10.1017/9781108778039
© Christian Hill 2015, 2020
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
Second edition 2020
Printed in the United Kingdom by TJ International Ltd, Padstow Cornwall
A catalogue record for this publication is available from the British Library.
ISBN 978-1-108-74591-8 Paperback
Additional resources for this publication at www.cambridge.org/hill2 and https://scipython.com/
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
vi Contents
6 NumPy 196
6.1 Basic Array Methods 196
6.2 Reading and Writing an Array to a File 228
6.3 Statistical Methods 239
6.4 Polynomials 246
6.5 Linear Algebra 261
6.6 Random Sampling 276
6.7 Discrete Fourier Transforms 287
7 Matplotlib 294
7.1 Line Plots and Scatter Plots 294
7.2 Plot Customization and Refinement 299
7.3 Bar Charts, Pie Charts and Polar Plots 314
7.4 Annotating Plots 323
7.5 Contour Plots and Heatmaps 336
7.6 Three-Dimensional Plots 348
7.7 Animation 352
8 SciPy 358
8.1 Physical Constants and Special Functions 358
8.2 Integration and Ordinary Differential Equations 381
8.3 Interpolation 408
8.4 Optimization, Data-Fitting and Root-Finding 414
Contents vii
Glossary 543
Index 549
Acknowledgments
Many people have helped directly or indirectly in the preparation of this book, in partic-
ular Jonathan Tennyson at UCL, and Laurence Rothman and Iouli Gordon for hosting
my sabbatical year at the Harvard-Smithsonian Center for Astrophysics.
Many of the errors and omissions in the first edition of this book were pointed out
by just a few people who were helpful enough to get in touch, notably Stafford Baines,
Matthew Gillman and Stuart Anderson. Those that remain are, of course, entirely my
own fault.
Special thanks are also due to Helen Reynolds, Chris Pickard, Alison Whiteley,
James Elliott, Lianna Ishihara and Milo Shaffer. As ever, I owe much to the support,
encouragement and friendship of Natalie Haynes.
viii
Code Listings
ix
x Code Listings
Code Listings xi
8.6 A comparison of the Lorentzian, Gaussian and Voigt line shapes 373
8.7 The spherical harmonic defined by l = 3, m = 2 377
8.8 Calculating the mass and center of mass of a tetrahedron given three differ-
ent densities 385
8.9 First-order reaction kinetics 387
8.10 Two coupled first-order reactions 390
8.11 Solution of the harmonic oscillator equation of motion 392
8.12 Calculating the motion of a sphere falling under the influence of gravity and
Stokes’ drag 394
8.13 Solution of the Robertson system of chemical reactions. 397
8.14 Calculating and plotting the trajectory of a spherical projectile including air
resistance. 400
8.15 A comparison of one-dimensional interpolation types using
scipy.interpolate.interp1d 408
8.16 Two-dimensional interpolation with scipy.interpolate.interp2d 410
8.17 Interpolation onto a regular two-dimensional grid with
scipy.interpolate.RectBivariateSpline 410
8.18 Interpolation from an unstructured array of two-dimensional points with
scipy.interpolate.griddata 412
8.19 Minimizing the drag on an airship envelope 423
8.20 Nonlinear least squares-fit to an ellipse 426
8.21 Weighted and unweighted least-squares fitting with curve_fit 428
8.22 Solution of the Euler–Lotka equation 432
8.23 Generating a Newton fractal image 433
9.1 Reading in a text table of vitamin data 454
9.2 The height of a projectile as a function of time 458
10.1 Comparison of different step sizes, h, in the numerical solution of y′ = −αy
by the forward Euler algorithm 499
R1
10.2 Comparison of algorithm stability in the calculation of I(n) = 0 xn e x dx 500
10.3 A function to calculate the volume of a tetrahedron 504
10.4 Code to simulate rolling two dice containing magic numbers 506
10.5 Code to simulate rolling two dice refactored to use named constants 506
10.6 A function for converting between different temperature units 510
10.7 Unit tests for the temperature conversion function 511
A.1 The structural formula of a straight-chain alkane 517
A.2 Least-squares fit to the function x = x0 + v0 t + 21 gt2 527
A.3 Calculating the probability of q or more misprints on a given page of a
book. 528
A.4 A comparison of the numerical behavior of f (x) = (1 − cos2 x)/x2 and
g(x) = sin2 x/x2 , close to x = 0. 534