Table Of ContentCiausFiihrer Jan Erik Solem Olivier Verdier
COMPUTING
WITH PYTHON
An introduction to Python for science and engineering
v M
-5
>•-, - >-«
> -
t -
*
X
> 5C
J
*c >
p -
>
s
V
p CP'
*
■*a*
*
05
ALWAYS LEARNING
PEARSON
COMPUTING WITH PYTHON
AN INTRODUCTION TO PYTHON FOR
SCIENCE AND ENGINEERING
PEARSON
At Pearson, we take learning personally. Our courses and
resources are available as books, online and via multi-lingual
packages, helping people learn whatever, wherever and
however they choose.
We work with leading authors to develop the strongest
learning experiences, bringing cutting-edge thinking and best
learning practice to a global market. We craft our print and
digital resources to do more to help learners not only
understand their content, but to see it in action and apply
what they learn, whether studying or at work.
Pearson is the world's leading learning company. Our portfolio
includes Penguin, Dorling Kindersley, the Financial Times and
our educational business, Pearson International. We are also
a leading provider of electronic learning programmes and
of test development, processing and scoring services to
educational institutions, corporations and professional bodies
around the world.
Every day our work helps learning flourish, and wherever
learning flourishes, so do people.
To learn more please visit us at: www.pearson.com/uk
COMPUTING WITH
PYTHON
AN INTRODUCTION TO PYTHON
FOR SCIENCE AND ENGINEERING
Claus Fuhrer, Jan Erik Solem and
Olivier Verdier
PEARSON
Harlow, England • London • New York • Boston • San Francisco • Toronto • Sydney • Auckland • Singapore • Hong Kong
Tokyo • Seoul • Taipei • New Delhi • Cape Town • Sao Paulo • Mexico City • Madrid • Amsterdam • Munich • Paris • Milan
PEARSON EDUCATION LIMITED
Edinburgh Gate
Harlow CM20 2JE
United Kingdom
Tel: +44 (0)1279 623623
Web; www.pearson.com/uk
First published 2014 (print and electronic)
© Pearson Education Limited 2014 (print and electronic)
The rights of Glaus Fiihrer, Jan Erik Solem and Olivier Verdier to be identified as authors of this work
have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988.
The print publication is protected by copyright. Prior to any prohibited reproduction, storage in a
retrieval system, distribution or transmission in any form or by any means, electronic, mechanical,
recording or otherwise, permission should be obtained from the publisher or, where applicable, a licence
permitting restricted copying in the United Kingdom should be obtained from the Copyright Licensing
Agency Ltd, Saffron House, 6-10 Kirby Street, London EC1N 8TS.
The ePublication is protected by copyright and must not be copied, reproduced, transferred,
distributed, leased, licensed or publicly performed or used in any way except as specifically permitted in
writing by the publishers, as allowed under the terms and conditions under which it was purchased, or
as strictly permitted by applicable copyright law. Any unauthorised distribution or use of this text may be
a direct infringement of the author's and the publishers' rights and those responsible may be liable in
law accordingly.
All trademarks used herein are the property of their respective owners. The use of any trademark in this
text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor
does the use of such trademarks imply any affiliation with or endorsement of this book by such owners.
'Python' is a registered trademark of the Python Software Foundation.
Pearson Education is not responsible for the content of third-party internet sites.
ISBN: 978-0-273-78643-6 (print)
British Library Cataloguing-in-Publication Data
A catalogue record for the print edition is available from the British Library
Library of Congress Cataloging-in-Publication Data
Fuhrer, Glaus.
Computing with Python : an introduction to Python for science and engineering / Glaus Fuhrer, Jan Erik
Solem and Olivier Verdier.
pages cm.
Includes bibliographical references and indexes.
ISBN 978-0-273-78643-6 (print: alkaline paper)
1. Python (Computer program language) 2. Science-Data processing. 3. Engineering-Data processing.
I. Solem, Jan Erik. II. Verdier, Olivier. III. Title.
QA76.73.P98F84 2013
005.13'3-dc23
2013025146
10 987654321
16 15 14 13
Print edition typeset in Stone Serif 9/11.5 by 73
Print edition printed and bound in Malaysia
NOTE THAT ANY PAGE CROSS REFERENCES REFER TO THE PRINT EDITION
BRIEF CONTENTS
Contents vii Chapter X Iterating 133
Preface ix
Chapter XI Error Handling 150
Chapter 1 Introduction 1
Chapter XII Namespaces, Scopes
Chapter II Getting Started 6 and Modules 162
Chapter III Variables and Basic Types 14 Chapter XIII Input and Output 168
Chapter IV Container Types 30 Chapter XIV Testing 175
Chapter V Linear Algebra: Arrays 44 Chapter XV Comprehensive Examples 189
Chapter VI Advanced Array Concepts 65
Appendix; Calling MATLAB from Python 203
Bibliography 206
Chapter VII Plotting 84
Python commands index 208
Chapter VIM Functions 101 Subject index 210
Chapter IX Classes 114
This page intentionally left blank
Contents vii V.8 Functions Acting on Arrays 57
Preface ix V.9 Linear Algebra Methods in SciPy 60
V.10 Exercises 62
Chapter 1 Introduction 1
Chapter VI Advanced Array Concepts 65
1.1 Python vs Other Languages 1
1.2 Literature 3 VI.1 Array Views and Copies 65
I.3 Installation and Configuration Instructions 3 VI.2 Comparing Arrays 66
1.4 Executing Scripts 4 VI.3 Array Indexing 69
VI.4 Performance and Vectorization 71
VI.5 Broadcasting 73
Chapter II Getting Started 6
VI.6 Sparse Matrices 79
II.1 Program and Program Flow 6
11.2 Basic Types 7
Chapter VII Plotting 84
11.3 Loops 10
11.4 Conditional Statements 11 VII.1 Basic Plotting 84
11.5 Functions 11 VII.2 Formatting 87
11.6 Scripts and Modules 12 VII.3 Images and Contours 91
11.7 Interpreter 13 VII.4 Useful Toolkits 93
VI 1.5 Exercises 99
Chapter III Variables and Basic Types 14
Chapter VIII Functions 101
111.1 Variables 14
III.2 Numeric Types 15 VIII.1 Basics 101
III.3 Booleans 21 VIII.2 Parameters and Arguments 102
III.4 Strings 24 VIII.3 Return Values 106
III.5 Exercises 27 VIII.4 Recursive Functions 107
VIII.5 Function Documentation 108
VIII.6 Functions are Objects 109
Chapter IV Container Types 30
VIII.7 Anonymous Functions - the lambda
I V.I Lists 30
Keyword 110
IV.2 Arrays 36
VIII.8 Functions as Decorators 112
IV.3 Tuples 37
VIII.9 Exercises 113
IV. 4 Dictionaries 38
IV.5 Sets 40
Chapter IX Classes 114
IV.6 Container Conversions and Summary 41
IV.7 Type Checking 41 IX.1 Introduction 115
IV.8 Exercises 42 IX.2 Attributes 116
IX.3 Subclassing and Inheritance 126
IX.4 Encapsulation 128
Chapter V Linear Algebra: Arrays 44
IX.5 Classes as Decorators 129
V.I Overview 44
IX.6 Exercises 131
V.2 Mathematical Preliminaries 47
V.3 The Array Type 49
Chapter X Iterating 133
V.4 Array Indexing 51
V.5 Functions to Construct Arrays 53 X.1 The for statement 133
V.6 Accessing and Changing the Shape 53 X.2 Iterators 135
V.7 Stacking 56
VIII Contents
X.3 List Filling Patterns 141 XIII.5 Reading and Writing Matlab Data Files 173
X.4 When Iterators Behave as Lists 144 XIII.6 Reading and Writing Images 173
X.5 Iterator Objects 145
X.6 Infinite Iterations 146 Chapter XIV Testing 175
X.7 Exercises 148
XIV. 1 Manual Testing 175
XIV.2 Automatic Testing 176
Chapter XI Error Handling 150
XIV.3 Measuring Execution Time 184
XI.1 Exceptions 150 XIV.4 Exercises 188
XI.2 Debugging 157
Chapter XV Comprehensive Examples 189
Chapter XII Namespaces,
XV.1 Polynomials 189
Scopes and Modules 162
XV.2 Spectral Clustering 196
XII.1 Namespace 162 XV.3 Solving Initial Value Problems 199
XII.2 Scope of a Variable 163 XV.4 Exercises 202
XII.3 Modules 164
Appendix: Calling MATLAB from Python 203
Chapter XIII Input and Output 168
Bibliography 206
XIII.1 File Handling 168
Python commands index 208
XIII.2 NumPy Methods 170
XIII.3 Pickling 171 Subject index 210
XIII.4 Shelves 172
PREFACE
This book is the outcome of a course on Python® for scientific computing which has been
taught at Lund University since 2008. The course expanded over the years, and condensed
versions of the material were taught at universities in Cologne, Trondheim, Stavanger,
Soran and also in computational oriented companies.
Our belief is that Python and its surrounding scientific computing ecosystem - SciPy,
NumPy and matplotlib - represent tremendous progress in the scientific computing en-
vironment. Python and the aforementioned libraries are free and open source. What's
more, Python is a modern language featuring all the bells and whistles that this adjective
entails: object oriented programing, testing, advanced Python shell with IPython, etc.
The typical reader of this book will already have some experience in programing, and
some taste for scientific computing or mathematics. Our goal is to explain to those readers
the steps to get started with Python in the context of scientific computing. The book
may be read either from the first page to the last, or by picking the bits that seem most
interesting. Needless to say, as improving one's programing skills requires considerable
practice, it is highly advisable to experiment and play with the examples and the exercises
in the book.
We hope that readers will enjoy programing with Python, SciPy, NumPy and matplotlib
as much as we do.
We would like to express our gratitude towards the reviewers of this book: Linda Kann,
KTH Stockholm, Hans Petter Langtangen, Simula Research Laboratory, and Alf Inge Wang,
NTNU Trondheim.
This book benefited from many helpful comments and suggestions by Helmut Pod-
haisky, Halle University, Tony Stillfjord and Christian Andersson, Lund University, and
students and teaching assistants from the course 'Berakningsprogramering med Python'
over the years.
Finally, we would like to express our thanks for the fruitful collaboration with the pub-
lisher during the production process, in particular to Philippa Fiszzon.
The Authors
September 27, 2013