0% found this document useful (0 votes)
3 views

Python_frontmatter

The book 'Learning Scientific Programming with Python' by Christian Hill provides a comprehensive introduction to programming using Python, focusing on scientific applications. It covers fundamental programming concepts, libraries like NumPy, SciPy, and Matplotlib, and includes a new chapter on data analysis with pandas in its second edition. The textbook is designed for students and researchers to quickly gain proficiency in Python for scientific programming tasks.

Uploaded by

BRANDON ALVARINO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python_frontmatter

The book 'Learning Scientific Programming with Python' by Christian Hill provides a comprehensive introduction to programming using Python, focusing on scientific applications. It covers fundamental programming concepts, libraries like NumPy, SciPy, and Matplotlib, and includes a new chapter on data analysis with pandas in its second edition. The textbook is designed for students and researchers to quickly gain proficiency in Python for scientific programming tasks.

Uploaded by

BRANDON ALVARINO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Cambridge University Press

978-1-108-74591-8 — Learning Scientific Programming with Python


Christian Hill
Frontmatter
More Information

Learning Scientific Programming with Python


Second Edition

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.

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

Learning Scientiic Programming


with Python
Second Edition

CHRISTIAN HILL

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

University Printing House, Cambridge CB2 8BS, United Kingdom


One Liberty Plaza, 20th Floor, New York, NY 10006, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
314–321, 3rd Floor, Plot 3, Splendor Forum, Jasola District Centre, New Delhi – 110025, India
79 Anson Road, #06–04/06, Singapore 079906

Cambridge University Press is part of the University of Cambridge.


It furthers the University’s mission by disseminating knowledge in the
pursuit of education, learning, and research at the highest international levels of excellence.

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.

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

Contents

Acknowledgments page viii


Code Listings ix

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

2 The Core Python Language I 8


2.1 The Python Shell 8
2.2 Numbers, Variables, Comparisons and Logic 9
2.3 Python Objects I: Strings 27
2.4 Python Objects II: Lists, Tuples and Loops 43
2.5 Control Flow 58
2.6 File Input/Output 68
2.7 Functions 71

3 Interlude: Simple Plots and Charts 86


3.1 Basic Plotting 86
3.2 Labels, Legends and Customization 91
3.3 More Advanced Plotting 100

4 The Core Python Language II 105


4.1 Errors and Exceptions 105
4.2 Python Objects III: Dictionaries and Sets 113
4.3 Pythonic Idioms: “Syntactic Sugar” 125
4.4 Operating-System Services 137
4.5 Modules and Packages 143
4.6 An Introduction to Object-Oriented Programming 152

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

vi Contents

5 IPython and Jupyter Notebook 172


5.1 IPython 172
5.2 Jupyter Notebook 186

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

9 Data Analysis with pandas 438


9.1 Introduction to pandas 438
9.2 Reading and Writing Series and DataFrames 452
9.3 More Advanced Indexing 462
9.4 Data Cleaning and Exploration 468
9.5 Data Grouping and Aggregation 479
9.6 Examples 483

10 General Scientific Programming 490


10.1 Floating-Point Arithmetic 490
10.2 Stability and Conditioning 498
10.3 Programming Techniques and Software Development 503

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

Contents vii

Appendix A Solutions 514

Appendix B Differences Between Python Versions 2 and 3 536

Appendix C SciPy’s odeint Ordinary Differential Equation Solver 540

Glossary 543
Index 549

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

Acknowledgments

For Emma, Charlotte and Laurence

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

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

Code Listings

1.1 Outputing a list of names using a program written in Python 2


1.2 Outputing a list of names using a program written in C 2
1.3 Different ways to output a list of names using a program written in Perl 3
2.1 Calculating the Fibonacci series in a list 53
2.2 Calculating the Fibonacci series without storing it 53
2.3 Determining if a year is a leap year 59
2.4 A virtual turtle robot 63
2.5 Python scope rules 76
2.6 The Tower of Hanoi problem 81
3.1 Plotting y = sin2 x 88
3.2 An illustration of Moore’s law 97
3.3 The correlation between margarine consumption in the United States and
the divorce rate in Maine 102
4.1 Astronomical data 117
4.2 The Mersenne primes 122
4.3 Issuing a usage message for a script taking command-line arguments 138
4.4 Renaming data files by date 141
4.5 The Monty Hall problem 147
4.6 The definition of the abstract base class, BankAccount 155
4.7 Polymer class 160
4.8 The distribution of random flight polymers 162
4.9 A simple class representing a two-dimensional Cartesian vector 164
4.10 A simple two-dimensional molecular dynamics simulation 166
6.1 Creating a magic square 205
6.2 Verifying the validity of a Sudoku square 213
6.3 argmax and argmin 217
6.4 Reading the blood-pressure column 231
6.5 Analyzing data from a Stroop effect experiment 234
6.6 Simulation of the radioative decay of 14 C 236
6.7 Calculating the correlation coefficient between air temperature and pressure 243
6.8 Liquid height in a spherical tank 250
6.9 Straight-line fit to absorbance data 257
6.10 Linear transformations in two dimensions 267

ix

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

x Code Listings

6.11 Linear least-squares fitting of the Beer–Lambert law 271


6.12 Modeling the distribution of 13 C atoms in C60 282
6.13 Blurring an image with a Gaussian filter 291
7.1 Scatter plot of demographic data for eight countries 299
7.2 The median age at first marriage in the US over time 301
7.3 The populations of five US cities over time 301
7.4 Exponential decay illustrated in terms of lifetimes 304
7.5 Customized tick marks 306
7.6 Wing-loading variation in swifts prior to fledging 308
7.7 The one-dimensional diffusion equation applied to the temperature of two
different metal bars 311
7.8 Ten subplots with zero vertical spacing 312
7.9 Letter frequencies in the text of Moby-Dick. 315
7.10 Visualizing renewable electricity generation in Germany 317
7.11 Pie chart of greenhouse gas emissions 319
7.12 Plotting the directive gain of a two-antenna system 321
7.13 Plotting the directive gain of a three-antenna system 321
7.14 Annotations with arrows in Matplotlib 325
7.15 Plotting a share price time series on an annotated chart 325
7.16 Some different ways to use ax.vlines and ax.hlines 328
7.17 A representation of the electromagnetic spectrum, 250–1000 nm 329
7.18 An analysis of the height–mass relationship in 507 healthy individuals 331
7.19 Some colorful shapes 333
7.20 The electrostatic potential of a point dipole 337
7.21 An example of filled and styled contours 338
7.22 A comparison of interpolation schemes for a small array visualized with
imshow() 340
7.23 Barnsley’s fern 341
7.24 Heatmap of Boston’s temperatures in 2019 342
7.25 The two-dimensional diffusion equation applied to the temperature of a
steel plate 344
7.26 Four three-dimensional plots of a simple two-dimensional Gaussian func-
tion 348
7.27 A three-dimensional surface plot of a torus 349
7.28 A depiction of a helix on a three-dimensional plot 351
7.29 An animation of a decaying sine curve 352
7.30 An animation of a decaying sine curve, using blit=True 354
7.31 An animation of a bouncing ball 355
8.1 Least-well-defined physical constants 360
8.2 Probability densities for a particle in a uniform gravitational field 362
8.3 Normal modes of a vibrating circular drum 365
8.4 Generating an image of the diffraction pattern of a uniform, continuous
helix 366
8.5 The Gamma function on the real line 368

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

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

© in this web service Cambridge University Press www.cambridge.org


Cambridge University Press
978-1-108-74591-8 — Learning Scientific Programming with Python
Christian Hill
Frontmatter
More Information

© in this web service Cambridge University Press www.cambridge.org

You might also like