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

Introduction to Python for Science and Engineering Second Edition David J. Pine - The ebook in PDF/DOCX format is available for instant download

The document is a promotional piece for the second edition of 'Introduction to Python for Science and Engineering' by David J. Pine, which provides a foundational understanding of Python programming tailored for scientific and engineering applications. It covers essential topics such as Python syntax, data structures, and numerical analysis, while also introducing popular libraries like NumPy and Matplotlib. Additionally, it includes links to download the book and other related ebooks from ebookultra.com.

Uploaded by

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

Introduction to Python for Science and Engineering Second Edition David J. Pine - The ebook in PDF/DOCX format is available for instant download

The document is a promotional piece for the second edition of 'Introduction to Python for Science and Engineering' by David J. Pine, which provides a foundational understanding of Python programming tailored for scientific and engineering applications. It covers essential topics such as Python syntax, data structures, and numerical analysis, while also introducing popular libraries like NumPy and Matplotlib. Additionally, it includes links to download the book and other related ebooks from ebookultra.com.

Uploaded by

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

Visit https://ebookultra.

com to download the full version and


explore more ebooks

Introduction to Python for Science and


Engineering Second Edition David J. Pine

_____ Click the link below to download _____


https://ebookultra.com/download/introduction-to-python-
for-science-and-engineering-second-edition-david-j-
pine/

Explore and download more ebooks at ebookultra.com


Here are some suggested products you might be interested in.
Click the link to download

Engineering mechanics an introduction to dynamics 4th


Edition David J. Mcgill

https://ebookultra.com/download/engineering-mechanics-an-introduction-
to-dynamics-4th-edition-david-j-mcgill/

Python Programming An Introduction to Computer Science


John M. Zelle

https://ebookultra.com/download/python-programming-an-introduction-to-
computer-science-john-m-zelle/

Introduction to biomedical engineering 3ed. Edition


Enderle J.

https://ebookultra.com/download/introduction-to-biomedical-
engineering-3ed-edition-enderle-j/

Introduction to Computing and Programming in Python a


Multimedia Approach Mark J. Guzdial

https://ebookultra.com/download/introduction-to-computing-and-
programming-in-python-a-multimedia-approach-mark-j-guzdial/
Introduction to Plasma Technology Science Engineering and
Applications 1st Edition John Ernest Harry

https://ebookultra.com/download/introduction-to-plasma-technology-
science-engineering-and-applications-1st-edition-john-ernest-harry/

Introduction to psycholinguistics understanding language


science Matthew J Traxler

https://ebookultra.com/download/introduction-to-psycholinguistics-
understanding-language-science-matthew-j-traxler/

Introduction to Fire in California Second Edition David


Carle

https://ebookultra.com/download/introduction-to-fire-in-california-
second-edition-david-carle/

Introduction To Materials Science And Engineering A Guided


Inquiry 1st Edition Elliot P. Douglas

https://ebookultra.com/download/introduction-to-materials-science-and-
engineering-a-guided-inquiry-1st-edition-elliot-p-douglas/

Introduction to chemical engineering thermodynamics 7rd ed


Edition J M Smith

https://ebookultra.com/download/introduction-to-chemical-engineering-
thermodynamics-7rd-ed-edition-j-m-smith/
Introduction to Python for Science and Engineering
Second Edition David J. Pine Digital Instant Download
Author(s): David J. Pine
ISBN(s): 9781032673950, 1032673958
File Details: PDF, 23.39 MB
Year: 2024
Language: english
Introduction to
Python for Science and
Engineering
Introduction to Python for Science and Engineering offers a quick and incisive
introduction to the Python programming language for use in any science or
engineering discipline. The approach is pedagogical and “bottom up,” which
means starting with examples and extracting more general principles from that
experience. No prior programming experience is assumed.
Readers will learn the basics of Python syntax, data structures, input and output,
conditionals and loops, user-defined functions, plotting, animation, and visual-
ization. They will also learn how to use Python for numerical analysis, including
curve fitting, random numbers, linear algebra, solutions to nonlinear equa-
tions, numerical integration, solutions to differential equations, and fast Fourier
transforms.
Readers learn how to interact and program with Python using JupyterLab and
Spyder, two simple and widely used integrated development environments.
All the major Python libraries for science and engineering are covered, includ-
ing NumPy, SciPy, Matplotlib, and Pandas. Other packages are also introduced,
including Numba, which can render Python numerical calculations as fast as
compiled computer languages such as C but without their complex overhead.
David J. Pine has taught physics and chemical engineering for over 40 years
at four different institutions: Cornell University (as a graduate student), Haver-
ford College, UCSB, and NYU, where he is a Professor of Physics, Mathematics,
and Chemical & Biomolecular Engineering. He has taught a broad spectrum of
courses, including numerical methods. He does research on optical materials
and in experimental soft-matter physics, which is concerned with materials such
as polymers, emulsions, and colloids.
Intelligent Data-Driven Systems and Artificial Intelligence
Series Editor: Harish Garg
Cognitive Machine Intelligence
Applications, Challenges, and Related Technologies
Inam Ullah Khan, Salma El Hajjami, Mariya Ouaissa, Salwa Belqziz and
Tarandeep Kaur Bhatia

Artificial Intelligence and Internet of Things based Augmented Trends for


Data Driven Systems
Anshu Singla, Sarvesh Tanwar, Pao-Ann Hsiung

Modelling of Virtual Worlds Using the Internet of Things


Edited by Simar Preet Singh and Arun Solanki

Data-Driven Technologies and Artificial Intelligence in Supply Chain


Tools and Techniques
Mahesh Chand, Vineet Jain and Puneeta Ajmera

For more information about this series, please visit: www.routledge.com/Intelli-


gent-Data-Driven-Systems-and-Artificial-Intelligence/book-series/CRCIDDSAAI
Introduction to
Python for Science and
Engineering
Second Edition

David J. Pine
Designed cover image: David J. Pine
MATLAB• and Simulink• are trademarks of The MathWorks, Inc. and are used with per-
mission. The MathWorks does not warrant the accuracy of the text or exercises in this
book. This book’s use or discussion of MATLAB• or Simulink• software or related prod-
ucts does not constitute endorsement or sponsorship by The MathWorks of a particular
pedagogical approach or particular use of the MATLAB• and Simulink•software.
Second edition published 2025
by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431

and by CRC Press


4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN

CRC Press is an imprint of Taylor & Francis Group, LLC

© 2025 David J. Pine

First edition published by CRC Press 2018

Reasonable efforts have been made to publish reliable data and information, but the author
and publisher cannot assume responsibility for the validity of all materials or the conse-
quences of their use. The authors and publishers have attempted to trace the copyright
holders of all material reproduced in this publication and apologize to copyright holders if
permission to publish in this form has not been obtained. If any copyright material has not
been acknowledged please write and let us know so we may rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted,
reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other
means, now known or hereafter invented, including photocopying, microfilming, and re-
cording, or in any information storage or retrieval system, without written permission
from the publishers.

For permission to photocopy or use material electronically from this work, access www.
copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood
Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please
contact [email protected]

Trademark notice: Product or corporate names may be trademarks or registered trade-


marks and are used only for identification and explanation without intent to infringe.

ISBN: 978-1-032-65033-3 (hbk)


ISBN: 978-1-032-67390-5 (pbk)
ISBN: 978-1-032-67395-0 (ebk)

DOI: 10.1201/9781032673950

Typeset in Nimbus font


by KnowledgeWorks Global Ltd.
To Alex Pine
who introduced me to Python
Contents

Preface to First Edition xvii

Preface to Second Edition xxi

About the Author xxiii

CHAPTER 1  Introduction 1
1.1 INTRODUCTION TO PYTHON FOR SCIENCE AND
ENGINEERING 1
1.2 INSTALLING PYTHON 3

CHAPTER 2  Launching Python 4


2.1 INTERACTING WITH PYTHON: THE IPYTHON SHELL 4
2.2 THE IPYTHON SHELL 6
2.3 INTERACTIVE PYTHON AS A CALCULATOR 6
2.3.1 Binary Arithmetic Operations in Python 7
2.3.2 Types of Numbers 7
2.3.3 Numbers as Objects 9
2.4 VARIABLES AND ASSIGNMENT 10
2.4.1 Names and the Assignment Operator 10
2.4.2 Legal and Recommended Variable Names 14
2.4.3 Reserved Words in Python 14
2.5 SCRIPT FILES AND PROGRAMS 15
2.5.1 Editors for Python Scripts 15
2.5.2 First Scripting Example 16
2.6 PYTHON MODULES 19
2.6.1 Python Modules and Functions: A First Look 20

vii
viii  Contents

2.6.2 Some NumPy Functions 22


2.6.3 Scripting Example 2 23
2.6.4 Different Ways of Importing Modules 24
2.7 GETTING HELP: DOCUMENTATION IN IPYTHON 25
2.8 PERFORMING SYSTEM TASKS WITH IPYTHON 26
2.8.1 Magic Commands 26
2.8.2 Tab Completion 29
2.8.3 Recap of Commands 30
2.9 PROGRAMMING ERRORS 30
2.9.1 Error Checking 30
2.10 EXERCISES 31

CHAPTER 3  Integrated Development Environments 33


3.1 PROGRAMMING AND INTERACTING WITH PYTHON 33
3.2 PROGRAMMING STYLE AND CODING ERRORS: PEP 8
AND LINTERS 34
3.3 THE SPYDER IDE 35
3.3.1 Autoformatting and Linting in Spyder 36
3.3.2 Running Python Code in Spyder 37
3.4 THE JUPYTERLAB IDE 39
3.4.1 Jupyter Extensions 41
3.5 JUPYTER NOTEBOOKS 43
3.6 LAUNCHING A JUPYTER NOTEBOOK 43
3.7 RUNNING PROGRAMS IN A JUPYTER NOTEBOOK 45
3.8 ANNOTATING A JUPYTER NOTEBOOK 45
3.8.1 Adding Headings and Text 46
3.8.2 Saving a Jupyter Notebook 48
3.8.3 Editing and Rerunning a Notebook 48
3.8.4 Quitting a Jupyter Notebook 49
3.8.5 Working with an Existing Jupyter Notebook 49

CHAPTER 4  Strings, Lists, Arrays, and Dictionaries 50


4.1 STRINGS 51
Contents  ix

4.1.1 Unicode Characters 52


4.2 LISTS 53
4.2.1 Slicing Lists 55
4.2.2 Multidimensional Lists 56
4.2.3 Appending to Lists 57
4.2.4 Tuples 58
4.3 DICTIONARIES 59
4.4 NUMPY ARRAYS 61
4.4.1 Creating Arrays (1-d) 61
4.4.2 Mathematical Operations with Arrays 63
4.4.3 Slicing and Addressing Arrays 66
4.4.4 Fancy Indexing: Boolean Indexing 67
4.4.5 Multidimensional Arrays and Matrices 69
4.4.6 Broadcasting 73
4.4.7 Differences Between Lists and Arrays 75
4.5 OBJECTS 76
4.6 EXERCISES 78

CHAPTER 5  Input and Output 83


5.1 KEYBOARD INPUT 83
5.2 SCREEN OUTPUT 85
5.2.1 Formatting Output with str.format() 85
5.2.2 Formatting with f-strings 89
5.2.3 Printing Arrays 89
5.3 FILE INPUT 91
5.3.1 Reading Data from a Text File 91
5.3.2 Reading Data from an Excel File: CSV Files 92
5.4 FILE OUTPUT 94
5.4.1 Writing Data to a Text File 94
5.4.2 Writing Data to a CSV File 96
5.5 EXERCISES 97
x  Contents

CHAPTER 6  Conditionals and Loops 100


6.1 CONDITIONALS 102
6.1.1 if, elif, and else Statements 102
6.1.2 More about Boolean Variables, Operators, and
Expressions 107
6.2 LOOPS 110
6.2.1 while Loops 110
6.2.2 for Loops 113
6.2.3 Loop Control Statements 118
6.2.4 Loops and Array Operations 119
6.3 LIST COMPREHENSIONS 120
6.4 HANDLING EXCEPTIONS 122
6.5 EXERCISES 125

CHAPTER 7  Functions 127


7.1 USER-DEFINED FUNCTIONS 128
7.1.1 Looping Over Arrays in User-Defined Functions 130
7.1.2 Fast Array Processing for User-Defined Functions 131
7.1.3 Functions with More than One Input or Output 133
7.1.4 Type Hints 134
7.1.5 Positional and Keyword Arguments 134
7.1.6 Variable Number of Arguments 136
7.1.7 Passing a Function Name and Its Parameters as
Arguments 137
7.2 NAMESPACE AND SCOPE IN PYTHON 140
7.2.1 Scope: Four Levels of Namespaces in Python 140
7.2.2 Variables and Arrays Created Entirely Within a
Function 142
7.2.3 Passing Lists and Arrays to Functions: Mutable and
Immutable Objects 143
7.3 ANONYMOUS FUNCTIONS: LAMBDA EXPRESSIONS 146
7.4 NUMPY OBJECT ATTRIBUTES: METHODS AND INSTANCE
VARIABLES 148
Contents  xi

7.5 EXAMPLE: LINEAR LEAST SQUARES FITTING 150


7.5.1 Linear Regression 151
2
7.5.2 Linear Regression with Weighting: χ 153
7.6 EXERCISES 155

CHAPTER 8  Plotting 163


8.1 AN INTERACTIVE SESSION WITH PYPLOT 164
8.2 BASIC PLOTTING 166
8.2.1 Specifying Line and Symbol Types and Colors 171
8.2.2 Error Bars 174
8.2.3 Setting Plotting Limits and Excluding Data 176
8.2.4 Subplots 179
8.3 LOGARITHMIC PLOTS 180
8.3.1 Semi-Log Plots 181
8.3.2 Log-Log Plots 183
8.4 MORE ADVANCED GRAPHICAL OUTPUT 183
8.4.1 An Alternative Syntax for a Grid of Plots 187
8.5 PLOTS WITH MULTIPLE AXES 189
8.5.1 Plotting Quantities that Share One Axis but not the
Other 189
8.5.2 Two Separate Scales for a Data Set 190
8.6 PLOTS WITH INSETS 191
8.7 MATHEMATICS AND GREEK SYMBOLS 193
8.7.1 Manual Axis Labeling 198
8.8 THE STRUCTURE OF MATPLOTLIB: OOP AND ALL THAT 199
8.8.1 The Backend Layer 200
8.8.2 The Artist Layer 202
8.8.3 The PyPlot (scripting) Layer 204
8.9 CONTOUR AND VECTOR FIELD PLOTS 206
8.9.1 Making a 2D Grid of Points 206
8.9.2 Contour Plots 207
8.9.3 Streamline Plots 211
xii  Contents

8.9.4 Vector Field (quiver) Plots 215


8.10 THREE-DIMENSIONAL PLOTS 217
8.10.1 Cartesian Coordinates 217
8.10.2 Polar Coordinates 219
8.11 EXERCISES 220

CHAPTER 9  Numerical Routines: SciPy and NumPy 225


9.1 SPECIAL FUNCTIONS 226
9.1.1 Important Note on Importing SciPy Subpackages 229
9.2 SPLINE FITTING, SMOOTHING, AND INTERPOLATION 229
9.2.1 Interpolating Splines 230
9.2.2 Smoothing Splines 234
9.2.3 Finding Roots (zero crossings) of Numerical Data 236
9.3 CURVE FITTING 236
9.3.1 Linear Fitting Functions 237
9.3.2 Polynomial Fitting Functions 240
9.3.3 Nonlinear Fitting Functions 242
9.4 RANDOM NUMBERS 247
9.4.1 Initializing NumPy’s Random Number Generator 247
9.4.2 Uniformly Distributed Random Numbers 247
9.4.3 Normally Distributed Random Numbers 248
9.4.4 Random Distribution of Integers 249
9.4.5 Poisson Distribution of Random Integers 249
9.5 LINEAR ALGEBRA 250
9.5.1 Basic Computations in Linear Algebra 251
9.5.2 Solving Systems of Linear Equations 251
9.5.3 Eigenvalue Problems 253
9.6 SOLVING NONLINEAR EQUATIONS 255
9.6.1 Single Equations of a Single Variable 255
9.6.2 Solving Systems of Nonlinear Equations 258
9.7 NUMERICAL INTEGRATION 258
9.7.1 Single Integrals of Functions 259
Contents  xiii

9.7.2 Double Integrals 263


9.7.3 Integrating Numerical Data 264
9.8 SOLVING ODES 265
9.8.1 A First-Order ODE 265
9.8.2 A Second-Order ODE 269
9.9 DISCRETE (FAST) FOURIER TRANSFORMS 273
9.9.1 Continuous and Discrete Fourier Transforms 273
9.9.2 The SciPy FFT Library 274
9.10 EXERCISES 276

CHAPTER 10  Python Classes: Encapsulation 284


10.1 A VERY SIMPLE CLASS 286
10.2 A BRIEF INTRODUCTION TO MODULES AND PACKAGES 290
10.2.1 Pythonpath 291
10.3 A CLASS FOR READING AND PROCESSING DATA 293
10.3.1 The Data 294
10.3.2 The Class 295
10.3.3 The Code 297
10.4 A CLASS OF RELATED FUNCTIONS 300
10.5 INHERITANCE 304
10.6 EXERCISES 305

CHAPTER 11  Data Manipulation and Analysis: Pandas 306


11.1 DATA STRUCTURES: SERIES AND DATAFRAME 307
11.1.1 Series 307
11.1.2 DataFrame 310
11.2 INDEXING DATAFRAMES 315
11.2.1 Pandas iloc Indexing 315
11.2.2 Pandas loc Indexing 316
11.3 READING DATA FROM FILES USING PANDAS 317
11.3.1 Reading from Excel Files Saved as CSV Files 317
11.3.2 Reading from an Excel File 324
11.3.3 Getting Data from the Web 326
xiv  Contents

11.4 EXTRACTING INFORMATION FROM A DATAFRAME 328


11.5 PLOTTING WITH PANDAS 332
11.6 GROUPING AND AGGREGATION 336
11.6.1 The groupby Method 337
11.6.2 Iterating Over Groups 338
11.6.3 Reformatting DataFrames 341
11.6.4 Custom Aggregation of DataFrames 343
11.7 EXERCISES 346

CHAPTER 12  Animation 351


12.1 ANIMATING A SEQUENCE OF IMAGES 351
12.1.1 Simple Image Sequence 352
12.1.2 Annotating and Embellishing Videos 355
12.2 ANIMATING FUNCTIONS 357
12.2.1 Animating for a Fixed Number of Frames 358
12.2.2 Animating until a Condition is Met 362
12.3 COMBINING VIDEOS WITH ANIMATED FUNCTIONS 368
12.3.1 Using a Single Animation Instance 368
12.3.2 Combining Multiple Animation Instances 370
12.4 EXERCISES 372

CHAPTER 13  Speeding Up Numerical Calculations 374


13.1 NUMBA’S BASIC FUNCTIONS 375
13.1.1 Faster Loops and NumPy Functions 376
13.1.2 Vectorizing Functions with Numba 382
13.1.3 Numba Signatures 383
13.2 SIMULATIONS 385
13.2.1 A Brownian Dynamics Simulation 385
13.2.2 Nondimensional Simulation Variables and
Parameters 387
13.2.3 Simulation with the Numba Decorator 389
13.2.4 Performance and Saving/Reading Large Data Files 392
13.2.5 Isolating Numerical Code for Numba 392
Contents  xv

13.3 USING NUMBA WITH CLASSES 393


13.4 OTHER FEATURES OF NUMBA 396
13.5 EXERCISES 396

Appendix A  Maintaining Your Python Installation 400


A.1 UPDATING PYTHON 400
A.2 TESTING YOUR PYTHON INSTALLATION 400
A.3 INSTALLING FFMPEG FOR SAVING ANIMATIONS 402
A.4 ADDING FOLDERS/DIRECTORIES TO YOUR PYTHON
PATH 402
A.4.1 Spyder 403
A.4.2 macOS 403
A.4.3 Windows 404
A.4.4 Linux 405

Appendix B  Glossary 406

Appendix C  Python Resources 409


C.1 PYTHON PROGRAMS AND DATA FILES INTRODUCED IN
THIS TEXT 409
C.2 WEB RESOURCES 409
C.3 BOOKS 410

Index 413
Preface to First Edition

The aim of this book is to provide science and engineering students a practi-
cal introduction to technical programming in Python. It grew out of notes I
developed for various undergraduate physics courses I taught at NYU. While
it has evolved considerably since I first put pen to paper, it retains its original
purpose: to get students with no previous programming experience writing
and running Python programs for scientific applications with a minimum of
fuss.
The approach is pedagogical and “bottom up,” which means starting with
examples and extracting more general principles from that experience. This
is in contrast to presenting the general principles first and then examples of
how those general principles work. In my experience, the latter approach is
satisfying only to the instructor. Much computer documentation takes a top-
down approach, which is one of the reasons it’s frequently difficult to read and
understand. On the other hand, once examples have been seen, it’s useful to
extract the general ideas in order to develop the conceptual framework needed
for further applications.
In writing this text, I assume that the reader:

• has never programmed before;

• is not familiar with programming environments;

• is familiar with how to get around a Mac or PC at a very basic level; and

• is competent in basic algebra, and for Chapters 8 and 9, calculus, linear


algebra, ordinary differential equations, and Fourier analysis. The other
chapters, including 10–12, require only basic algebra skills.

This book introduces, in some depth, four Python packages that are im-
portant for scientific applications:

NumPy, short for Numerical Python, provides Python with a multidimen-


sional array object (like a vector or matrix) that is at the center of virtu-
ally all fast numerical processing in scientific Python. It is both versatile

xvii
xviii  Preface to First Edition

and powerful, enabling fast numerical computation that, in some cases,


approaches speeds close to those of a compiled language like C, C++,
or Fortran.
SciPy, short for Scientific Python, provides access through a Python interface
to a very broad spectrum of scientific and numerical software written in
C, C++, and Fortran. These include routines to numerically differentiate
and integrate functions, solve differential equations, diagonalize matri-
ces, take discrete Fourier transforms, perform least-squares fitting, as
well as many other numerical tasks.
Matplotlib is a powerful plotting package written for Python and capable of
producing publication-quality plots. While there are other Python plot-
ting packages available, Matplotlib is the most widely used and is the de
facto standard.
Pandas is a powerful package for manipulating and analyzing data formatted
and labeled in a manner similar to a spreadsheet (think Excel). Pandas
is very useful for handling data produced in experiments and is partic-
ularly adept at manipulating large data sets in different ways.
In addition, Chapter 12 provides a brief introduction to Python classes
and to PyQt5, which provides Python routines for building graphical user in-
terfaces (GUIs) that work on Macs, PCs, and Linux platforms.
Chapters 1–7 provide the basic introduction to scientific Python and
should be read in order. Chapters 8–12 do not depend on each other and,
with a few mild caveats, can be read in any order.
As the book’s title implies, the text is focused on scientific uses of Python.
Many of the topics that are of primary importance to computer scientists, such
as object-oriented design, are of secondary importance here. Our focus is on
learning how to harness Python’s ability to perform scientific computations
quickly and efficiently.
The text shows the reader how to interact with Python using IPython,
which stands for Interactive Python, through one of three different interfaces,
all freely available on the web: Spyder, an integrated development environ-
ment, Jupyter Notebooks, and a simple IPython terminal. Chapter 2 provides
an overview of Spyder and an introduction to IPython, which is a powerful
interactive environment tailored to scientific use of Python. Appendix B pro-
vides an introduction to Jupyter notebooks.
Python 3 is used exclusively throughout the text with little reference to
any version of Python 2. It’s been nearly 10 years since Python 3 was intro-
duced, and there is little reason to write new code in Python 2; all the major
Preface to First Edition  xix

Python packages have been updated to Python 3. Moreover, once Python 3


has been learned, it’s a simple task to learn how Python 2 differs, which may
be needed to deal with legacy code. There are many lucid web sites dedicated
to this sometimes necessary but otherwise mind-numbing task.
The scripts, programs, and data files introduced in this book are available
at https://github.com/djpine/python-scieng-public-2, the GitHub site for this
book.
Finally, I would like to thank Étienne Ducrot, Wenhai Zheng, and Stefano
Sacanna for providing some of the data and images used in Chapter 12, and
Mingxin He and Wenhai Zheng for their critical reading of early versions of
the text.
Preface to Second Edition

The aim of the second edition remains the same as the first: to provide science
and engineering students a practical introduction to technical programming
in Python. This new edition adds nearly 100 pages of new material.
Among the changes, the concept of an object is developed more thor-
oughly, starting in Chapter 2 with the discussion of variables and assignment.
This perspective is continued throughout the text as the various aspects of ob-
jects are revealed and developed. The chapter on Python classes, now Chapter
10, has been completely rewritten with new examples. Here, we emphasize the
concept of encapsulation and its use in science and engineering.
Chapter 3 on the Spyder and Jupyter Lab integrated development environ-
ments (IDEs) is new. Some of the material on the Spyder IDE can be found in
the First Edition, but it has been updated and expanded in this edition. The
material on the Jupyter Lab IDE is entirely new, as Jupyter Lab has developed
significantly since the first edition and now offers a compelling IDE.
New examples have been added to Chapter 6 on conditionals and loops.
The chapter also includes a new section on exception handling.
The introduction of functions has been moved so that it now occurs be-
fore the chapter on plotting. Type hints, new to Python since the first edition,
are discussed. The subtle subject of namespace and scope and its relation to
functions has been expanded significantly.
The chapter on curve fitting has been eliminated. That material is now
covered in Chapters 7 and 9.
New material has been added to Chapter 8 on plotting, including an in-
troduction to the Seaborn package. New examples have been added, includ-
ing using two separate scales for a single axis, plots with insets, vector field
(quiver) plots, and plotting with polar coordinates.
Chapter 9 on the NumPy and SciPy packages has been expanded to in-
clude new material on interpolating and smoothing splines. Several updates
in various NumPy and SciPy packages have been incorporated into the text,
including changes in NumPy’s random number and polynomial packages.

xxi
xxii  Preface to Second Edition

Chapter 13 on speeding up numerical computations is new. It focuses on


the Numba package and how to effectively use it to address Python’s Achilles’
heel, its slow execution of long loops involving numerical code.
The programs and data files introduced in the Second Edition are available
at https://github.com/djpine/python-scieng-public-2.
The paper edition is printed in grayscale to reduce costs. However,
the original figures in full color are available at https://github.com/djpine/
python-scieng-public-2.
In addition to those who contributed to the First Edition, I would like
to thank Marc Gershow for helpful suggestions, Fan Cui for initial versions
code presented in Chapter 13, and Xinhang Shen for providing data used in
Chapter 8.
About the Author

David Pine has taught Physics and Chemical Engineering for more than 40
years at four different institutions: Cornell University (as a graduate student),
Haverford College, UCSB, and NYU, where he is a Professor of Physics, Math-
ematics, and Chemical and Biomolecular Engineering. He has taught a broad
spectrum of courses, including numerical methods. He does research on opti-
cal materials and soft-matter physics, which is concerned with materials such
as polymers, emulsions, and colloids.

xxiii
CHAPTER 1

Introduction

1.1 INTRODUCTION TO PYTHON FOR SCIENCE AND


ENGINEERING
This book is meant to serve as an introduction to the Python programming
language and its use for scientific computing. It’s ok if you have never pro-
grammed a computer before. This book will teach you how to do it from the
ground up.
Python is well suited for most scientific and engineering computing tasks.
You can use it to analyze and plot data. You can also use it to numerically solve
science and engineering problems that are difficult or even impossible to solve
analytically.
While we want to marshal Python’s powers to address scientific problems,
you should know that Python is a general-purpose computer language widely
used for a broad spectrum of computing tasks, from web applications to pro-
cessing financial data on Wall Street and various scripting tasks for computer
system management. Over the past decade, it has been increasingly used by
scientists and engineers for numerical computations and graphics and as a
“wrapper” for numerical software originally written in other languages, like
Fortran and C.
Python is similar to MATLAB®, another computer language frequently
used in science and engineering applications. Like MATLAB®, Python is an
interpreted language, meaning you can run your code without going through
an extra step of compiling, as required for the C and Fortran programming
languages. It is also a dynamically typed language, meaning you don’t have to
declare variables and set aside memory before using them.

DOI: 10.1201/9781032673950-1 1
2  Introduction to Python for Science and Engineering

Don’t worry if you don’t know exactly what these terms mean.1 Their pri-
mary significance for you is that you can write Python code, test it, and use it
quickly with a minimum of fuss.
One advantage of Python compared to MATLAB® is that it is free. It can be
downloaded from the web and is available on all the standard computer plat-
forms, including Windows, macOS, and Linux. This also means that you can
use Python without being tethered to the internet, as required for commercial
software tied to a remote license server.
Another advantage is Python’s clean and simple syntax, including its im-
plementation of object-oriented programming. This should not be discounted;
Python’s rich and elegant syntax renders many tasks that are difficult or arcane
in other languages more straightforward and understandable in Python.
A significant disadvantage is that Python programs can be slower than
compiled languages like C. For large-scale simulations and other demanding
applications, there can be a considerable speed penalty in using Python. In
these cases, C, C++, or Fortran are recommended, although intelligent use of
Python’s array processing tools in the NumPy module can significantly speed
up Python code. Alternatively, several new tools have recently appeared that
can be used to speed up certain numerical computations in Python signifi-
cantly, often by one or two orders of magnitude. These are discussed in Chap-
ter 13. Another disadvantage is that, compared to MATLAB®, Python is less
well-documented. This stems from the fact that it is public open source soft-
ware and thus depends on volunteers from the community of developers and
users for documentation. The documentation is freely available on the web
but is scattered among a number of different sites and can be terse. This book
will acquaint you with the most commonly used websites. Search engines like
Google can help you find others.
You are not assumed to have had any previous programming experience.
However, the purpose of this manual isn’t to teach you the principles of com-
puter programming; it’s to provide a very practical guide to getting started
with Python for scientific computing. Once you see some of the powerful
tasks you can accomplish with Python, perhaps you will be inspired to study
computational science and engineering, as well as computer programming, in
greater depth.

1
Appendix B contains a glossary of terms you may find helpful.
Introduction  3

1.2 INSTALLING PYTHON


You need to install Python and four scientific Python libraries for scientific
programming with Python: NumPy, SciPy, Matplotlib, and Pandas. You can
install many other useful libraries, but these four are the most widely used
and are the only ones you will need for this text.
There are several ways to install Python and the necessary scientific li-
braries. Some are easier than others. For most people, the simplest way to
install Python and all the scientific libraries you need is to use the Ana-
conda distribution, which includes the JupyterLab and Spyder integrated de-
velopment environments (IDEs) for Python. These IDEs are introduced in
Chapter 3.
The Anaconda distribution package can be found at the website
https://www.anaconda.com/download/. Once you download and install it,
you can use the Anaconda-Navigator application to launch all of the applica-
tions introduced in this text, including Spyder, JupyterLab, and Qt Console.
Now, you are ready to go.
CHAPTER 2

Launching Python

In this chapter, you learn about IPython, an interface that allows you
to use Python interactively with tools optimized for mathematical and
computational tasks. You learn how to use IPython as a calculator to
add, subtract, multiply, divide, and perform other common mathemat-
ical functions. You also learn the basic elements of the Python program-
ming language, including functions, variables, and scripts, which are
rudimentary computer programs. You are introduced to Python mod-
ules, which extend the capabilities of the core Python language and al-
low you to perform advanced mathematical tasks. You also learn some
new ways to navigate your computer’s file directories. Finally, you learn
how to get help with Python commands and functions.

2.1 INTERACTING WITH PYTHON: THE IPython SHELL


There are many different ways to interact with Python. For simple comput-
ing tasks, people typically use the Python command shell, which is also called
the Python interpreter or console. A shell or console is just a window on your
computer that you use to issue written commands from the keyboard. For sci-
entific Python, which is the focus of this text, people generally use the IPython
shell (or console) instead of the Python shell. The IPython shell is specifically
designed for scientific and engineering use. We use the IPython shell through-
out this text.
To launch a Python or IPython shell, you first need to launch a terminal
application. If you are running the macOS, launch the Terminal application,
which you can find in the Applications/Utilities folder on your computer. If

4 DOI: 10.1201/9781032673950-2
Launching Python  5

Figure 2.1 Qt console for IPython.

you are running Windows, launch the Anaconda Powershell Prompt application
from the Start menu. Under Linux, you can open the Terminal application by
pressing <ctrl + alt + T>.
After launching a terminal application, type jupyter qtconsole at the
terminal prompt and press <return>. This launches a particularly powerful
version of the IPython shell called the Qt Console. Alternatively, instead of
launching a terminal, you can launch Qt Console directly from the Anaconda-
Launcher app that is downloaded with the Anaconda Python Distribution. The
Qt Console for IPython will be used throughout this text. It should look like
the window in Figure 2.1. You should see the default input prompt of the
IPython shell, which looks like this:
In[1]:

Now you are ready to go.


By the way, if you type ipython at the terminal prompt, you will get a sim-
ilar but less powerful IPython shell. This is not what you want. If you type
python at the terminal prompt, you get the standard Python shell with the
prompt:
>>>

This is not what you want either. Type quit() after the >>> prompt to quit the
Python shell and return to the system terminal. By the way, you can also type
quit() to quit either of the IPython shells and return to the system terminal.
6  Introduction to Python for Science and Engineering

2.2 THE IPython SHELL


The IPython prompt, shown here,
In[1]:

indicates that the IPython shell is running and ready to receive input from
the user (you!). By typing commands at the prompt, IPython can be used to
perform various tasks, such as running programs, performing arithmetic, and
creating and moving files around on your computer.
Before getting started, we note that, like most modern computer lan-
guages, Python is case sensitive. That is, Python distinguishes between upper-
and lower-case letters. Thus, two words spelled the same but having different
letters capitalized are treated as different names in Python. Please keep that in
mind in all that follows.

2.3 INTERACTIVE PYTHON AS A CALCULATOR


Let’s get started. You can use the IPython shell to perform simple arithmetic
calculations. For example, to find the product 3 × 15, you type 3*15 (or 3 * 15,
spaces don’t matter) at the In prompt and press <return>:
In[1]: 3 * 15
Out[1]: 45

Python returns the correct product, as expected. You can do more complicated
calculations:
In[2]: 6 + 21 / 3
Out[2]: 13.0

Let’s try some more arithmetic:


In[3]: (6 + 21) / 3
Out[3]: 9.0

Notice that the effect of the parentheses in In[3]: (6 + 21) / 3 is to cause the
addition to be performed first and then the division. Without the parenthe-
ses, Python will always perform the multiplication and division operations be-
fore performing the addition and subtraction operations. The order in which
arithmetic operations are performed is the same as for most calculators: expo-
nentiation first, then multiplication or division, then addition or subtraction,
then left to right.
Launching Python  7

TABLE 2.1 Binary operators.


Operation Symbol Example Output
Addition + 19 + 7 26
Subtraction - 19 - 7 12
Multiplication * 19 * 7 133
Division / 19 / 7 2.7142857142
Floor division // 19 // 7 2
Remainder % 19 % 7 5
Exponentiation ** 19**7 893871739

2.3.1 Binary Arithmetic Operations in Python


Table 2.1 lists the binary arithmetic operations in Python. Python has all the
standard binary operators for arithmetic, plus a few you may not have seen
before.
“Floor division,” designated by //, means divide and keep only the integer
part without rounding. “Remainder,” designated by the symbol %, gives the
remainder after floor division.

2.3.2 Types of Numbers


There are three different types of numbers in Python: Integers, floating point
numbers, and complex numbers.

1. Integers in Python are simply, as their name implies, integers. They can
be positive or negative and can be arbitrarily long. In Python, a number
is automatically treated as an integer if it is written without a decimal
point. This means that 23, written without a decimal point, is an integer,
and 23., written with a decimal point, is a floating point number. Here
are some examples of integer arithmetic:
In[4]: 12 * 3
Out[4]: 36

In[5]: 4 + 5 * 6 - (21 * 8)
Out[5]: -134

In[6]: 11 / 5
Out[6]: 2.2

In[7]: 11 // 5 # floor divide


Out[7]: 2
8  Introduction to Python for Science and Engineering

In[8]: 9734828*79372
Out[8]: 772672768016

For the binary operators +, -, *, and //, the output is an integer if the
inputs are integers. The output of the division operator / is a floating
point number (as of version 3 of Python). The floor division operator //
must be used if an integer output is desired when dividing two integers.
2. Floating point numbers are essentially rational numbers and can have
a fractional part; integers, by their very nature, have no fractional part.
In most versions of Python, floating point numbers go between approx-
imately ±2 × 10−308 and ±2 × 10308 . Here are some examples of floating
point arithmetic:
In[9]: 12. * 3
Out[9]: 36.0

In[10]: 12 / 3.
Out[10]: 4.0

In[11]: 5 ** 0.5
Out[11]: 2.23606797749979

In[12]: 5 ** (1/2)
Out[12]: 2.23606797749979

In[13]: 11. / 5.
Out[13]: 2.2

In[14]: 11. // 5.
Out[14]: 2.0

In[15]: 11. % 5.
Out[15]: 1.0

In[16]: 6.022 e23 * 300.


Out[16]: 1.8066 e+26

Note that the result of any operation involving only floating point num-
bers as inputs is another floating point number, even in cases where the
floor division // or remainder % operators are used. The last output illus-
trates an alternative way of writing floating point numbers as a mantissa
followed by e or E followed by a power of 10: so 1.23e-12 is equivalent
to 1.23 × 10−12 .
Notice also that multiplying or dividing a floating point number by an
integer produces a floating point number.
Launching Python  9

We used the exponentiation operator ** to find the square root of 5 by


using a fractional power of 0.5 and 1/2. In Section 2.6.2, an alternative
method is presented for finding the square root of a number.

3. Complex numbers are written in Python as a sum of real and imaginary


parts. For example, the complex
√ number 3 − 2i is represented as 3-2j in
Python, where j represents −1. Here are some examples of complex
arithmetic: 2+3j * -4+9j = 2+(3j * -4)+9j = (2-3j), whereas (2+3j) *
(-4+9j) = (-35+6j).
In[17]: (2+3j) * ( -4+9j)
Out[17]: ( -35+6j)

In[18]: (2+3j) / ( -4+9j)


Out[18]: (0.1958762886597938 -0.3092783505154639 j)

In[19]: 2.5 -3j**2


Out[19]: (11.5+0 j)

In[20]: (2.5 -3j)**2


Out[20]: ( -2.75 -15j)

Notice that 2.5-3j**2 and (2.5-3j)**2 give different results. You need to
enclose the real and imaginary parts of a complex number in parenthe-
ses if you want exponentiation to operate on the entire complex number
and not simply on the imaginary part. It works similarly with multipli-
cation and division of complex numbers, so be sure to enclose the en-
tire complex number with parentheses if you wish to multiply or divide
complex numbers.
If you multiply an integer by a floating point number, the result is a float-
ing point number. If you multiply a floating point number by a complex
number, the result is a complex number. Python promotes the result to
the most complex of the inputs.

2.3.3 Numbers as Objects


Everything in Python is an object. Thus, the numbers we introduced above are
all objects. We will not fully define what an object is right now; we will explain
it little by little as needed as we proceed.
The first thing to know about objects is that they are the fundamental
things that Python manipulates and works with. As such, they have some in-
teresting properties, a few of which we explore here. For example, each object
10  Introduction to Python for Science and Engineering

has an ID, which is just its location in your computer’s memory. We can de-
termine the ID of an object using Python’s id function.
In[21]: id (52)
Out[21]: 140294301609872

In[22]: id (241.3)
Out[22]: 140293508419248

In[23]: id (3+7j)
Out[23]: 140293508416368

The next thing to know is that every object has a type, which can be as-
certained using the function type. So, what are the types of the numbers we
introduced above?
In[24]: type (72)
Out[24]: int

In[25]: type ( -11.4)


Out[25]: float

In[26]: type (3 -36j)


Out[26]: complex

The results are not too surprising: int for integers, float for floating point
numbers, and complex for complex numbers.
An object’s type defines how it interacts with other objects. For exam-
ple, you can freely add, subtract, multiply, and divide objects of the types int,
float, and complex, as illustrated above. On the other hand, you can’t multiply
float and complex types by a string type such as “dog” (we introduce strings in
Chapter 4). Trying to do so will result in an error message. Surprisingly, you
can multiply strings by int types, but we defer that discussion to Section 4.1.

2.4 VARIABLES AND ASSIGNMENT


2.4.1 Names and the Assignment Operator
A variable is a way of associating a name with an object. Thus, when we write
In[1]: a = 32

Python binds the variable name a to the integer object 32. The equals sign = is
the assignment operator, and its function is to bind the variable name on the
left side to the object on its right side.
Consider the following code:
In[2]: leg_a = 3.7
Launching Python  11

19.53
leg_a = 19.53

leg_a 3.7 leg_a 3.7

leg_b 8.3 leg_b 8.3

hypotenuse 9.08... hypotenuse 9.08...

Figure 2.2 Binding variable names to objects.

In[3]: leg_b = 8.3

In[4]: hypotenuse = (leg_a **2 + leg_b **2)**0.5

In[5]: hypontenuse
Out[5]: 9.087353850269066

The first two statements bind the variable names leg_a and leg_b to the float
objects 3.7 and 8.3, respectively. The third statement performs the calculation
to the right of the equals sign and then binds the variable name hypotenuse to
the resulting float object 9.087353850269066. Note that Python binds the result
of the calculation, not the calculation itself, to the variable hypotenuse. There-
fore, if we reassign the value of leg_a to a new value, the value of hypotenuse
does not change, as demonstrated here.
In[6]: leg_a = 19.53

In[7]: hypotenuse
Out[7]: 9.087353850269066

When we write leg_a = 19.53, Python reassigns the variable name leg_a to
a new float object 19.53, as illustrated in Figure 2.2. The old object, in this
case, the float 3.7, is still in memory. Eventually, Python gets rid of it to free
up memory; this process is called garbage collection and occurs behind the
scenes so that you do not need to worry about it.
The assignment operator “=” in Python is not equivalent to the equals
sign “=” you are accustomed to in algebra. Consider the following sequence
of commands.
In[8]: a = 5
12  Introduction to Python for Science and Engineering

In[9]: a = a + 2

In[10]: a
Out[10]: 7

The statement a = a + 2 makes no sense in algebra. But it makes perfect sense


in Python (and in most computer languages). It means take the current value
of a, add 2 to it, and assign the result to the variable name a. Python reassigns
the variable name a to a new object, with a value of 7 in this case.
This construction appears so often in programming that there is a special
set of operators dedicated to performing such changes to a variable: +=, -=, *=,
and /=. For example, a = a + 2 and a += 2 do the same thing; they add 2 to
the current value of a. Here are some other examples of how these operators
work:
In[11]: c = 4

In[12]: c += 3

In[13]: c
Out[13]: 7

In[14]: c *
= 3

In[15]: c
Out[15]: 21

In[16]: d = 7.92

In[17]: d /= -2

In[18]: d
Out[18]: -3.96

In[19]: d -= 4

In[20]: d
Out[20]: -7.96

By the way, %=, **=, and //=, are also valid operators. Verify in the IPython
console that you understand how the above operations work.
Python also allows you to make multiple variable assignments in a single
statement
In[21]: p, q, r = 32.1 , 81.6 , 111.6

is equivalent to p = 32.1, q = 81.6, and r = 111.6. Having made that assign-


ment, what do you think p, q, r = r, p, q does? Try it out for yourself and
Launching Python  13

see if you were able to predict the correct results. The key thing to remember
is that Python evaluates the right-hand side of the equation before assigning
the results to the left-hand side.
Finally, please note that the same object can have multiple names. For ex-
ample, in the following code, a and b point to (i.e., are bound to) the same
object, which you can verify by checking the ID of each of them.
In[22]: a = b = 3.4

In[23]: id(a)
Out[23]: 140293508599056

In[24]: id(b)
Out[24]: 140293508599056

In[25]: b = 5.8

In[26]: id(b)
Out[26]: 140293508598928

In[27]: id(a)
Out[27]: 140293508599056

Reassigning b to a different value creates a new object with a new ID distinct


from the ID of a, which remains the same after the reassignment of b.
We also point out here that an object doesn’t have to have a name associ-
ated with it. For example, when we write
In[28]: 5 * 6
Out[28]: 30

none of the objects for 5, 6, or 30 have names. They are all integer objects.
Not having variable names associated with them, we say that they are integer
literals.

2.4.1.1 Python Variables are Dynamically Typed


By the way, suppose that in the last step above, we had written b = 6 instead
of b = 5.8. Before trying this out, let’s first check the variable b’s type. Then we
will reassign the value of b by typing b = 6.
In[29]: type(b)
Out[29]: float
In[30]: b = 6

In[31]: type(b)
Out[31]: int
14  Introduction to Python for Science and Engineering

Notice that after we wrote b = 6, its type changed from float to int. This fea-
ture of Python is called dynamical typing. A variable’s type can change on the
fly. That’s all we’ll say about dynamic typing for now, but we will return to this
topic.

2.4.2 Legal and Recommended Variable Names


Variable names in Python must start with a letter or an underscore “_” and
can be followed by as many alphanumeric characters as you like, including
the underscore character “_”. Spaces are not allowed in variable names. No
other character that is not a letter, number, or underscore is permitted.
Although variable names can start with the underscore character, you
should avoid doing so except in special cases, which we discuss in Chapter
10.
Recall that Python is case sensitive, so the variable velocity is distinct from
the variable veLocity. We recommend giving your variables descriptive names
as in the following calculation:
In[32]: distance = 34.

In[33]: time_traveled = 0.59

In[34]: velocity = distance / time_traveled

In[35]: velocity
Out[35]: 57.6271186440678

Giving variables descriptive names serves two purposes. First, it makes


the code (to some extent) self-documenting so that you or another reader
of the code can get some idea about what it does. The variable names
distance, time_traveled, and velocity immediately remind you of what is
being calculated here. Second, it can help you catch errors; if we had writ-
ten velocity = time_traveled / distance, you might be more likely to notice
that something’s amiss. So, using descriptive variable names is good practice.
But so is keeping variable names reasonably short, so don’t go nuts! When us-
ing two words for a variable name, it’s considered good practice in Python to
connect the two words with an underscore (e.g., time_traveled).

2.4.3 Reserved Words in Python


Python reserves certain names or words for special purposes. These names are
provided in Table 2.2 for your reference. You must avoid using these names as
variables.
Launching Python  15

TABLE 2.2 Reserved names in Python.


False None True and as
assert async await break class
continue def del elif else
except finally for from global
if import in is lambda
nonlocal not or pass raise
return try while with yield
__peg_parser__

2.5 SCRIPT FILES AND PROGRAMS


Performing calculations in the IPython shell is handy if the calculations are
short. But calculations quickly become tedious when they are over a few lines
long. If you discover that you made a mistake at some early step, for example,
you may have to go back and retype all the steps subsequent to the error. Hav-
ing code saved in a file means you can correct the error and rerun the code
without having to retype it. Saving code can also be useful if you want to reuse
it later, perhaps with different inputs.
For these and many other reasons, we save code in computer files. The se-
quence of Python commands stored in a file is called a script or a program or
sometimes a routine. Programs can become quite sophisticated and complex.
In this chapter, we introduce only the simplest features of programming by
writing a very simple script. Later, we will introduce some of the more ad-
vanced features of programming.

2.5.1 Editors for Python Scripts


Python scripts are just plain text files. The only requirement is that the file-
name ends with .py. Because they are just plain text files, you can write Python
scripts using any simple text editor. No special editor is required. Some edi-
tors, however, automatically recognize any file whose name ends in the suffix
.py as a Python file. For example, the text editors Notepad++ (for PCs), BBE-
dit (for Macs), and Gedit (for Linux) automatically recognize Python files. All
three editors work very well and are available without charge on the internet.
These editors are nice because they color code the Python syntax, a helpful
feature called syntax highlighting. They also have other programming-specific
features that make the files easy to read and edit. Other editors have similar
features, and they also work very well.
16  Introduction to Python for Science and Engineering

Note, however, that word processing programs like Microsoft Word® are
not suitable for this purpose because they produce files that, in addition to the
visible text, contain all sorts of formatting code that is invisible to the user but
not the computer (or the Python interpreter). You must use a plain text editor.

2.5.1.1 Create a Directory (Folder) for Python Scripts


You should create a directory (also known as a folder) on your computer to
store your Python scripts. For example, you might create a directory called
PyScripts inside the Documents directory. If possible, choose a filename with
no spaces in it. Avoiding spaces in directory names is not absolutely necessary
but, as you will see below, it can simplify navigation between directories.

2.5.2 First Scripting Example


Let’s work through an example to see how scripting works. Suppose you are
going on a road trip and would like to estimate how long the drive will take,
how much electricity you will need (you’re driving an EV), and the cost of the
electricity. It’s a simple calculation. As inputs, you will need the trip’s distance,
your average speed, the cost of electricity, and the mileage (average miles per
kilowatt-hour) for your car.
Writing a script to do these calculations is straightforward. First, launch
a text editor, which can be one of the three mentioned above, Notepad++,
BBEdit, or Gedit, depending on your operating system, or some other text
editor of your choosing. Enter the following code and save the code. Do not
include the small numbers 1–10 in the left margin. These are just for reference
and are not part of the Python code.

Code: my_trip.py
1 """ Calculates time , electrical energy used , and cost of electricity
2 for a trip in an electric vehicle """
3 # Get inputs
4 distance = 180. # [ miles ]
5 mpk = 3.9 # [ miles /kilowatt -h] car mileage
6 speed = 60. # [ miles /h] average speed
7 cost_per_kWh = 0.22 # [$/kW -h] price of electricity
8
9 # Calculate outputs
10 time = distance / speed # [ hours ]
11 energy = distance / mpk # [kW -h]
12 cost = energy * cost_per_kWh # [$]

Save the file with the name my_trip.py in the directory PyScripts that you
created earlier (see Section 2.5.1.1). This stores your script (or program) on
your computer’s disk. More generally, the name of a Python file can be almost
Launching Python  17

anything consistent with the computer operating system as long the name ends
with the extension .py. The .py extension tells the computer this is a Python
program.
The code in the program is pretty straightforward: lines 4–7 set the values
of the inputs, while lines 10–12 calculate the desired information. All of the
variables are floats by virtue of the decimal point included in each assignment
statement. Notice that we included a blank line, line 8, between the input and
output blocks of code. This is not necessary, as the blank line serves no compu-
tational purpose. Rather, it indicates to the reader that the blocks do different
things, analogous to what paragraphs do in normal written text.
The text between the triple quotes at the beginning of the program is called
a “docstring” and is not executed when the script is run. Everything between
the triple quotes is part of the docstring, which can extend over multiple lines,
as it does here. It’s a good idea to include a docstring explaining what your
script does at the beginning of your file.
The hash (or number) symbol # is the “comment” character in Python;
anything on a line following # is ignored when the code is executed. A com-
ment in a Python script is a brief explanation or annotation added to help
people reading the program understand what the program is doing. Judicious
use of comments in your code will make it much easier to understand days,
weeks, or months after you write it. Use comments generously. For aesthetic
reasons, the comments on different lines have been aligned. This isn’t neces-
sary. The spaces needed to align the comments have no effect on the running
of the code.
Now you are ready to run the code. From a QtConsole, type
In[1]: run ~/ Documents / PyScripts / my_trip .py

The string of text ~/Documents/PyScripts/ tells IPython where your script is


located on your computer: the tilde ~ designates the user’s home directory,
which might correspond to something like /Users/dp on a macOS or Linux
computer, or C:\Users\dp on a Windows computer. You don’t need to write
out the name of your home directory; just writing ~ will do. Next comes the hi-
erarchy of directories, each separated by a forward slash (for any operating sys-
tem, MacOs, Windows, or Linux), where the Python script is located, and then
finally the name of the file my_trip.py containing the script. If a directory name
contains one or more spaces, such as My Files, for example, then on Mac you
should write cd ~/Documents/My\ Files or cd "~/Documents/My Files". That is,
you can either replace each space by a backslash and a space or you can en-
close the entire path in quotes, either single ' or double ". On a PC, you can
include a space without taking any special measures.
18  Introduction to Python for Science and Engineering

When you run a script, Python executes the sequence of commands in the
order they appear. Afterward, you can see the values of the variables calculated
in the script by typing the name of the variable. IPython responds with the
value of that variable. For example:
In[2]: time
Out[2]: 3.0

In[3]: energy
Out[3]: 46.15384615384615

In[4]: cost
Out[4]: 10.153846153846153

Of course, you must remember that the time is in hours, and the cost is in U.S.
dollars.
You can change the number of digits IPython displays using the com-
mand %precision. To display two digits to the right of the decimal place, enter
%precision 2:
In[5]: % precision 2
Out[5]: ' %.2f'

In[6]: time
Out[6]: 3.00

In[7]: energy
Out[7]: 46.15

In[8]: cost
Out[8]: 10.15

Typing %precision returns IPython to its default state; %precision %e causes


IPython to display numbers in exponential format (scientific notation).

2.5.2.1 Note about Printing


If you want your script to return the value of a variable (that is, print the value
of the variable to your computer screen), use the print function. For example,
at the end of our script, if we include the code
print (time)
print ( energy )
print (cost)

the script will return the values of the variables time, gallons, and cost that
the script calculated. We will discuss the print function in much greater detail,
as well as other methods for data output, in Chapter 5.
Launching Python  19

2.6 PYTHON MODULES


The Python computer language consists of a “core” language plus a vast col-
lection of supplementary software that is contained in modules (or packages,
which are collections of modules—we’ll not fuss about the distinction here).
Many of these modules come with the standard Python distribution and pro-
vide added functionality for performing computer system tasks. Other mod-
ules provide more specialized capabilities that only some users may want.
These modules are a kind of library from which you can borrow according
to your needs. You gain access to a module using the import command, which
we introduce in the next section.
We will need four Python modules that are not part of the core Python
distribution but are widely used for scientific computing. The four modules
are:

NumPy is the standard Python package for scientific computing with Python.
It provides the all-important NumPy array data structure, which is
at the very heart of NumPy. It also provides tools for creating and
manipulating arrays, including indexing and sorting, as well as ba-
sic logical operations and element-by-element arithmetic operations
like addition, subtraction, multiplication, division, and exponentia-
tion. It includes the basic mathematical functions of trigonometry,
exponentials, and logarithms, as well as a vast collection of special
functions (Bessel functions, etc.), statistical functions, and random
number generators. It also includes many linear algebra routines that
overlap with those in SciPy, although the SciPy routines tend to be
more comprehensive. You can find more information about NumPy at
http://docs.scipy.org/doc/numpy/reference/index.html.

SciPy provides a broad spectrum of mathematical functions and numerical


routines for Python. SciPy makes extensive use of NumPy arrays, so
when you import SciPy, you should always import NumPy too. In addi-
tion to providing basic mathematical functions, SciPy provides Python
“wrappers” for numerical software written in other languages, like For-
tran, C, or C++. A “wrapper” provides a transparent easy-to-use Python
interface to standard numerical software, such as routines for perform-
ing curve fitting and numerically solving differential equations. SciPy
dramatically extends the power of Python and saves you the trouble
of writing software in Python that someone else has already written
and optimized in some other language. You can find more information
about SciPy at http://docs.scipy.org/doc/scipy/reference/.
20  Introduction to Python for Science and Engineering

Matplotlib is the standard Python package for making two- and three-
dimensional plots. Matplotlib makes extensive use of NumPy arrays. All
of the plots in this book use this package. You can find more informa-
tion about Matplotlib at the website http://matplotlib.sourceforge.net/.

Pandas is a Python package providing a powerful set of data analysis tools.


It uses data structures similar to those used in a spreadsheet pro-
gram like Excel and allows you to manipulate data in ways simi-
lar to spreadsheets. You can find more information about Pandas at
http://pandas.pydata.org/.

We will use these four modules extensively and, therefore, will provide in-
troductions to their capabilities as we develop Python. The links above provide
much more extensive information; you will certainly want to refer to them oc-
casionally.

2.6.1 Python Modules and Functions: A First Look


Because the modules listed above, NumPy, SciPy, Matplotlib, and Pandas, are
not part of core Python, they must be imported before we can access their
functions and data structures. Here, we show how to import the NumPy mod-
ule and use some of its functions. We defer introducing NumPy arrays, men-
tioned in the previous section, until Section 4.4.
You gain access to the NumPy package using Python’s import statement:
In[1]: import numpy

After running this statement, you can access all the functions and data struc-
tures of NumPy. For example, you can now access NumPy’s sine function as
follows:
In[2]: numpy.sin (0.5)
Out[2]: 0.479425538604203

In this simple example, the sin function has one argument, here 0.5, and the
function returns the sine of that argument, which must be expressed in radi-
ans.
Note that we had to put the prefix numpy dot before the name of the actual
function name sin. This tells Python that the sin function is part of the NumPy
module that we just imported.
Another Python module called math also has a sine function. We can im-
port the math module just like we imported the NumPy module:
In[3]: import math
Another Random Scribd Document
with Unrelated Content
105. R u n d k e h r e i m S e i t e n t a l
zur Vermeidung zu starker Steigung im Haupttal

Auch die Strecke über den Brennerpaß besitzt eine Anlage dieser
Art. Hier zeigt die Eisenbahn einmal, daß sie schwerfälliger ist als die
Landstraße. Zu Fuß gelangt man von Schellenberg nach Gossensaß weit
schneller als im Abteil des D-Wagens. Die Landstraße steigt zwischen
den in der Luftlinie nur 1100 Meter voneinander entfernten Orten
ziemlich geradlinig hinunter. Die Bahn aber muß sich, um 176 Meter tief
in das Tal der Eisack zu gelangen, seitlich weit in das Pflerschtal
hineinwenden, da ihr die unmittelbare Überwindung einer Neigung von
1 : 6 versagt ist. Sieben Kilometer werden hier — vom reinen
Verkehrsstandpunkt betrachtet — unnötig durchfahren, aber nun
beträgt die größte Neigung auf der ganzen Strecke nur 1 : 45.
Seitentäler sind jedoch nicht immer zur Verfügung. Alsdann muß
die künstliche Längenentwicklung in dem von der Bahn benutzten
Haupttal selbst stattfinden. Dies gibt Anlaß zu den großartigsten und
überraschendsten Bauten, insbesondere dann, wenn doch eine
Seitenentwicklung durch die höchst merkwürdige Anlage von
Kehrtunneln gewaltsam ermöglicht wird.
In diesen Bauarten hat die Bahn über den St. Gotthard zum
erstenmal besonders Hervorragendes geleistet.
In der Nähe des Pfaffensprungs steigt das hier sehr schmale,
beiderseits von ragenden Felsen eingeschlossene Tal der Reuß weit
rascher auf, als daß die Bahn der Talhebung ohne weiteres zu folgen
vermöchte. Es ist hier auch keine Gelegenheit, irgendwohin ohne
weiteres auszubiegen, und so mußte eine Seitenausladung dadurch
erzwungen werden, daß man in den Berg selbst einen eigenartig
geformten Tunnel hineintrieb, der nun also die ansteigende
Seitentalschleife zu ersetzen hat. In dem rückkehrenden Tunnel muß
daher eine allmähliche Hebung der Bahn stattfinden, so daß dieser die
Form einer Schraubenlinie mit Einer Windung erhält. Bei der Einfahrt in
den Pfaffensprung-Berg liegt die Bahn 774 Meter hoch, bei der Ausfahrt
hat sie 809 Meter erreicht, so daß sie im Berg um 35 Meter gestiegen
ist.
Solcher großen Kehrtunnel, in denen die Bahn steigend ihre
Fahrtrichtung einmal umkehrt, besitzt die Gotthardbahn jenseits des
großen Scheiteltunnels noch vier, von denen die zwei in der Biaschina-
Schlucht liegenden einander fast berühren. Dies schon ist ein besonders
deutliches Zeichen dafür, welche außerordentlichen Umwege einer
Gebirgsbahn mit gewöhnlichem Anhaftungsgleis zugemutet werden
dürfen, ohne daß dessen Vorteile gegenüber dem Zahngleis verloren
gehen.
Der größte Umweg, den die Gotthardstrecke macht, befindet sich
jedoch bei dem Ort Wasen, bald hinter dem Pfaffensprung. Hier sind die
nicht ganz geschlossenen Kehrtunnelschlingen als Enden zweier langer
Schleifen in dem breiten Haupttal ausgebildet. In drei Stockwerken
liegen die Bahnabschnitte in kühnstem Bau übereinander. Da die
Umkehr der Fahrtrichtung an den Enden der beiden Schleifen in
verdeckten Kehren, nämlich im Wattinger und Leggistein-Tunnel
stattfindet, so daß sie mit dem Auge nicht verfolgt werden kann,
vermag der Reisende, der keine Karte zur Hand hat, sich keine
Vorstellung von dem Weg der Bahn zu machen. Welche Verwirrung die
dreimalige Rückkehr zu dem gleichen Punkt in manchem Kopf
anzustiften vermag, zeigt eine bekannte Anekdote, deren Schauplatz die
Wasener Schleifenstrecke ist.

106. K e h r t u n n e l
Bahnsteigung in einem Berg
107a. K e h r e n d e r G o t t h a r d b a h n b e i F a i d o u n d D a z i o
Grande

107b. D o p p e l k e h r e d e r G o t t h a r d b a h n i n d e r
Biaschina-Schlucht

Ein Reisender, der des Landes unkundig ist, fährt zusammen mit
einem Schweizer in einem Abteil des Gotthardzugs. Nachdem der
Pfaffensprung-Kehrtunnel verlassen ist, fragt der Reisende den
Schweizer, indem er zum rechtsliegenden Fenster hinausdeutet. „Was ist
das für ein Bauwerk da oben?“ — „Das ist die Kirche von Wasen,“ lautet
die Antwort. Es vergeht etwa eine Viertelstunde, und der Fremde sieht
ein Gebäude dicht neben sich. „Und was ist dies?“ fragt er wieder. „Das
ist die Kirche von Wasen,“ sagt der Schweizer. Der Fremde glaubt nicht
recht gehört zu haben, denn dieselbe Antwort hatte er ja schon vor
einer Viertelstunde erhalten, und damals lag die Kirche hoch über der
Bahn. Stumm blickt er weiter hinaus, bis er plötzlich wiederum einen
Turm weit unter sich, und zwar auf der linken Seite, erblickt. „Und diese
Kirche dort, wie heißt sie?“ spricht er den Mitreisenden von neuem an.
„Das ist die Kirche von Wasen,“ lautet die Antwort. Nun aber wird der
Reisende wütend, er blickt den Schweizer zornig an, weil er glaubt, daß
dieser ihn zum Narren halten wolle, und richtet während der ganzen
Zeit, in der sie noch zusammen im Abteil sitzen, kein Wort mehr an ihn.

108a) D o p p e l s c h l e i f e d e r G o t t h a r d b a h n b e i W a s e n
108b) B l i c k a u f W a s e n m i t d e n d r e i
übereinanderliegenden
E i s e n b a h n l i n i e n (×)

In der Wasener Doppelschleife, deren Anfangs- und Endpunkte in


der Geraden nur drei Kilometer voneinander entfernt sind, steigt die
Bahn um 256 Meter.
Der Zweck all dieser Kehren und Schleifen ist die Erreichung des
eigentlichen Gebirgsdurchbruchs, des großen, meist ganz gerade durch
die Gebirgsmasse hindurchführenden Tunnels. Man muß diese Bauten
notgedrungen in eine gewisse Höhe legen, da sie näher am Fuß des
Gebirges zu lang werden würden und auch der Druck des
übergelagerten Gebirges beim Bau kaum zu bewältigen wäre. Bis zu
welcher Höhe man jedesmal hinaufgehen soll, ist Sache oft sehr langer
und beschwerlicher Erwägungen. Die großen Gebirgstunnel liegen denn
auch in sehr verschiedenen Höhen.
Am höchsten von allen Bahnlinien klettert die Peruanische
Zentralbahn Callao-Lima-Oroya hinauf. Der Galera-Tunnel, in dem sie die
südamerikanischen Anden durchfährt, liegt 4774 Meter über dem
Meeresspiegel. Das ist fast die Höhe des Mont Blanc, dessen Gipfel
4810 Meter emporragt. Man vermag in Peru die Geleise so hoch
hinaufzuführen, weil dort, nicht allzuweit vom Äquator, die Grenze des
ewigen Schnees in einer Höhe von 5000 Metern liegt, während die
Alpen schon von 2800 Metern ab vereist sind.
Eine Fahrt mit der Peruanischen Andenbahn wird als ein besonderer
Naturgenuß gerühmt. Es ist jedoch keine reine Freude, die man hierbei
genießt. Denn schon in einer Höhe von 4000 Metern beginnt die
Bergkrankheit sich bemerkbar zu machen. Die Eisenbahn klettert trotz
aller Umwege viel zu schnell empor, als daß der menschliche Körper Zeit
hätte, sich langsam an den verminderten Luftdruck zu gewöhnen. So
stellen sich denn, ehe noch der Galera-Tunnel erreicht ist, bei den
meisten Reisenden Atemnot, Herzklopfen und eine sehr unangenehme
Mattigkeit in den Gliedern ein. Wenn der Zug in Oroya angelangt ist,
füllt sich das dortige Hotel meist rasch mit Kranken, die einige Stunden
brauchen, um sich wieder zu erholen. So nehmen die Gewalten, welche
das heutige Antlitz der Erde schufen, dem Menschen einen großen Teil
des Genusses wieder fort, den der Anblick der ungeheuren
Gebirgsbildungen ihm zu gewähren vermag.
Die höchste Lage von allen Eisenbahnen in Europa — abgesehen
von den eigentlichen Bergstrecken — erreicht die Brennerbahn mit 1367
Metern über dem Meeresspiegel. Über den Brenner läuft der älteste
Verkehrsweg zwischen Nordeuropa und Italien, weil hier die tiefste
Alpeneinsattelung liegt. Aus demselben Grund wurde an dieser Stelle
auch der erste Schienenweg über das gewaltige Gebirge gelegt. Die
Brennerbahn ist die einzige von allen Alpenüberschienungen, die keinen
großen Durchbruchstunnel besitzt. Die Paßhöhe wird vielmehr in einem
offenen Einschnitt überschritten. Dies bedeutet einen großen Vorzug der
Brennerbahn, sowohl was die Baukosten, als was die Annehmlichkeiten
für die Reisenden bedeutet. Die Vermeidung eines Tunnelbaus ist
jedoch nur möglich, wenn die Schienenoberkante, wie hier, nicht tiefer
als 15 Meter unter den Bergrücken gelegt werden muß. Von da ab
würde die Herstellung eines Einschnitts zu teuer werden.
Die weltberühmten großen Alpendurchstiche haben folgende
Höhenlagen:
Arlberg (Schweiz-Österreich) 1320 Meter
Mont Cenis (Schweiz-Frankreich) 1294 Meter
Lötschberg (Nordwest-Schweiz-Italien) 1245 Meter
Gotthard (Nordost-Schweiz-Italien) 1154 Meter
Simplon (Südwest-Schweiz-Italien) 704 Meter.
Durch diese gewaltigen Bauten hat die Schweiz ihr Land an die großen
zwischenstaatlichen Verkehrswege angeschlossen.

Simplon-Tunnel erbaut von 1898 bis 1905


für die Eisenbahn Genua-Genf
Längster Tunnel der Erde
St Gotthard-Tunnel, erbaut von 1872 bis 1881
für die Eisenbahn Mailand-Zürich.

Lötschberg-Tunnel, erbaut von 1906 bis 1912


für die Eisenbahn Genua-Basel

Mont Cenis-Tunnel, erbaut von 1857 bis 1871


für die Eisenbahn Turin-Lyon

Arlberg-Tunnel erbaut von 1880 bis 1884


für die Eisenbahn Innsbruck-Bregenz
Kaiser Wilhelm-Tunnel bei Kochem
erbaut von 1874 bis 1878
für die Eisenbahn Koblenz-Trier
Längster Tunnel in Deutschland

Hauenstein-Tunnel
erbaut von 1853 bis 1857
für die Eisenbahn Basel-Olten

Semmering-Tunnel
erbaut von 1849 bis 1852
für die Eisenbahn Wien-Triest
Nach einer Tafel im Deutschen Museum zu München
109. V e r g l e i c h e n d e A n g a b e n ü b e r d i e w i c h t i g s t e n
Tu n n e l b a u t e n

In diesem Zusammenhang muß noch der Bahn über den


Semmering besondere Erwähnung getan werden, da sie in den Jahren
1848-1854 als erste große Gebirgsbahn des europäischen Festlands
erbaut wurde. Sie dient der Verbindung zwischen Wien und dem großen
Adriahafen Triest. Alle Gebirgsbahnbauer auf der Erde haben aus dieser
Anlage gelernt; was hier geschaffen war, wurde unmittelbar zum Vorbild
für die Überschienung des Schwarzwalds und alsdann der Alpen.
Infolge ihrer verschiedenen Höhenlagen haben die großen
Alpentunnel auch verschiedene Längen. Außer beim Mont Cenis-
Durchstich wächst die Länge mit abnehmender Höhenlage. Die Längen
betragen in abgerundeten Zahlen:
beim Arlberg-Tunnel 10 Kilometer
beim Mont Cenis-Tunnel 12 Kilometer
beim Lötschberg-Tunnel 14 Kilometer
beim Gotthard-Tunnel 15 Kilometer
beim Simplon-Tunnel 20 Kilometer.
Dieser letzte ist der bei weitem längste Tunnel auf der Erde.
Der Bau eines Tunnels wird stets mit einem sogenannten
Richtstollen begonnen. Es ist dies ein schmaler, niedriger Durchbruch in
der gewählten Richtung, der nur gerade so viel Raum bietet, daß man
darin arbeiten und das geförderte Gestein hinausschaffen kann. Vom
Richtstollen aus wird dann die Ausweitung nach allen Seiten hin
vorgenommen. Der endgültige Querschnitt muß so groß sein, daß
jederzeit, ohne Beeinträchtigung des Bahnverkehrs, ein Gerüst für
Ausbesserungsarbeiten im Tunnel aufgeschlagen werden kann.
Der Bau wird, damit man nicht allzuviel Zeit aufzuwenden braucht,
stets von beiden Seiten zugleich begonnen. Dies setzt eine
allergenaueste Feststellung der Richtung voraus, da die beiden Stollen
ja in der Mitte zusammentreffen müssen. Mit Recht ist diese Richtungs-
Festlegung eine der am meisten bewunderten Leistungen menschlichen
Geistes. Ihre Grundlagen seien ganz kurz angegeben.
Die beiden Tunneltore liegen bei den großen Bauten stets so, daß
man von dem einen aus weder das andere, noch irgendeinen Punkt von
dessen Umgebung wahrzunehmen vermag. Man kann auch nicht eine
Vermessungslinie über den Bergrücken legen und von dort etwa
Bohrlöcher hinuntertreiben, da deren Länge viel zu groß werden würde
und furchtbare Abgründe, sowie die Vergletscherung das Betreten des
zwischenliegenden Bergrückens an vielen Stellen unmöglich machen. Es
muß daher eine mittelbare Verbindung hergestellt werden. Deren Ziel
ist, auf beiden Seiten den Winkel festzulegen, den die gewählte
Tunnelrichtung mit je einer bekannten Linie im Gelände bilden muß.

110. M e s s u n g e n v o r B e g i n n e i n e s g r o ß e n
Tu n n e l b a u s v o n b e i d e n S e i t e n
Festlegung der Tunnelrichtung durch trigonometrische Aufnahme im Gelände
Wir wollen, um ein Beispiel zu geben, annehmen, daß aus der
nächsten Umgebung des Punkts, an dem das eine Tunneltor errichtet
werden soll, eine Landstraße mit vielen Windungen in die Nähe des
andren Tors hinüberführt, wie das auf Bild 110 der Fall ist. Man kann
alsdann diese Landstraße genau abmessen, die Länge jeder gradlinigen
Erstreckung festlegen und mit Hilfe der trigonometrischen Hilfsmittel
auch ganz genau den Winkel bestimmen, den jede geänderte Richtung
zu der vorhergehenden bildet. Nach Beendigung dieser Arbeit ist man
imstande, die Landstraße mit vollkommener Genauigkeit in eine Karte
einzuzeichnen. Verbindet man nun die beiden Anfangspunkte des
Tunnels durch eine gerade Linie und verlängert diese so weit nach
beiden Seiten, bis sie die eingezeichnete Landstraße schneidet, so kann
man auf der Karte den Winkel abmessen, den die Tunnelachse zu den
geschnittenen Landstraßenstücken diesseits und jenseits bilden muß.
Damit liegt die Richtung genau fest, und es kommt jetzt nur darauf an,
sie auch im Gelände abzustecken und beim Bau aufs genaueste
innezuhalten.
Zu diesem Zweck wird zunächst auf jeder Seite der von der Karte
entnommene Winkel zwischen dem letzten Straßenstück und der
Tunnelachse abgemessen, und es werden zwei starke Pfosten in der
genauen Tunnelrichtung in die Erde gesetzt. Auf ihnen werden die
Richtungs-Festpunkte angebracht. Alsdann wird hinter dem ersten
Pfosten ein Fernrohr aufgestellt, in dem ein senkrechter und ein
wagerechter Faden, das Fadenkreuz, so angebracht sind, daß sie
einander genau in der Mittelachse des Fernrohrs kreuzen. Man richtet
das Fernrohr so, daß seine Mittelachse genau in der Richtung der
Verbindungslinie liegt, die von dem Festpunkt des ersten Pfostens zum
zweiten führt.
Wenn man nun an der Bergwand eine kleine Lampe derartig
aufhängt, daß sie beim Schauen durch das so eingestellte Fernrohr
gerade im Kreuzungspunkt der beiden Fäden erscheint, dann ist damit
der Anfang der Tunnelachse bestimmt. Sobald der Richtstollen ein
kleines Stückchen vorgetrieben ist, läßt man von der Decke wiederum
ein Lämpchen hinunterhängen und verschiebt es so lange, bis der durch
das Fernrohr Blickende es in gerader Linie hinter den beiden
Pfostenmarken und der ersten Lampe liegen sieht. So wird allmählich
Lampe hinter Lampe gehängt, neue mit vollkommenster Genauigkeit
festgelegte Pfostenmarken werden auch im Tunnel in gewissen
Abständen immer wieder geschaffen, und auf diese Weise ist man
imstande, von beiden Seiten aus die Achsrichtung innezuhalten.
Die Genauigkeit der Richtungshaltung hängt natürlich von der
Vollkommenheit der verwendeten Winkelmessungswerkzeuge ab. Bei
dem vor kurzem von der deutschen Firma Julius Berger in der Schweiz
gebauten neuen Hauenstein-Tunnel, der 8200 Meter lang ist, betrug
beim Durchschlag die Achsabweichung der beiden Bauseiten nicht mehr
als zwei Zentimeter; selbst bei dem 20 Kilometer langen Simplontunnel
waren es nur 20 Zentimeter. Der Meßtechnik kann kein glänzenderes
Zeugnis ausgestellt werden als durch diese eindrucksvollen Tatsachen.
Der Tunnel muß so gebaut werden, daß seine Sohle von beiden
Seiten her gegen die Mitte etwas ansteigt, damit das Wasser, sowohl
zugeführtes wie auch angeschlagenes Gebirgswasser, abfließen kann.
Für die Heranschaffung von Frischluft zur Lüftung und Kühlung muß
während der ganzen Bauzeit in lebhaftester Weise Sorge getragen
werden. Sobald der Durchschlag erfolgt ist, pflegen sich die Tunnel,
insbesondere durch die Mithilfe der fahrenden Züge, selbst zu lüften, da
zwischen den beiden Toren gewöhnlich ein starker Unterschied des
Luftdrucks besteht. Wenn die Selbstlüftung nicht ausreicht, müssen, wie
beim Kochemer Tunnel und auch auf dem Gotthard, künstliche
Luftzuführungs-Einrichtungen geschaffen werden.
Die Tunnelbaukunst ist in den letzten Jahrzehnten lebhaft
vervollkommnet worden. Früher mußte man die zur Aufnahme des
Sprengstoffs dienenden Bohrlöcher mit der Hand herstellen. Ein Arbeiter
drehte den Bohrer, eine mit stählerner Spitze versehene Eisenstange,
während ein anderer daraufschlug. Sehr viel geschwinder arbeiten
natürlich Bohrmaschinen, von denen die ersten beim Mont Cenis-Tunnel
verwendet wurden. Heute besitzt man vorzügliche Einrichtungen dieser
Art, die durch Preßwasser, Druckluft oder Elektrizität betrieben werden
können. Auch die Maschinenbohrer arbeiten sämtlich so, daß die
Bohrstange zugleich gestoßen und gedreht wird. Man vermag heute
mehrere Löcher zu gleicher Zeit herzustellen, und da auch die Wirkung
der Sprengstoffs bedeutend vervollkommnet ist, wodurch man mit einer
immer geringeren Zahl von Löchern auskommen kann, so vollziehen
sich die Tunnelbauten immer rascher. Beim Gotthard-Tunnel vermochte
man in den günstigsten Monaten nur um je 111 Meter vorwärts zu
kommen, beim Arlberg-Tunnel brachte man es schon auf 166 Meter im
Monat, und der Simplon-Tunnel wurde in der gleichen Zeit um je 270
Meter vorgetrieben.

Nach einer Tafel im Deutschen Museum zu München


111. Z a h l d e r B o h r l ö c h e r b e i v e r s c h i e d e n e n
Tu n n e l b a u t e n
Durch Verbesserung der Sprengmittel ist die Zahl der für jede Sprengung
notwendigen Bohrlöcher rasch geringer geworden

Noch deutlicher sprechen die folgenden Zahlen. Für die Herstellung


des im Jahre 1880 durchgeschlagenen, 15 Kilometer langen Gotthard-
Tunnels brauchte man 8 Jahre, für den 1871 vollendeten, um 3
Kilometer kürzeren Mont Cenis-Tunnel sind 13 Jahre Bauzeit notwendig
gewesen. Der 20 Kilometer lange Simplon-Tunnel ist von der Hamburger
Firma Brandt, Brandau & Co. trotz vieler unerwarteter Hindernisse in
nur 61⁄2 Jahren hergestellt worden. Die Gesamtkosten betrugen 78
Millionen Franken.
Welche Schwierigkeiten bei der Führung eines Tunnels durch eine
gewaltige Gebirgsmasse zu überwinden sind, welch furchtbare Kämpfe
der Mensch hierbei mit den unterirdischen Gewalten auszufechten hat,
die ihm immer neue Hindernisse in den Weg stellen, zeigt am besten
eine Schilderung vom Bau des Simplon-Tunnels, den die
schweizerischen Bundesbahnen veröffentlicht haben:
„Bald erhöhte der Berg die Wärme im Innern zu unerträglicher
Hitze, bald schob er heimtückisch weiches, bröckelndes Gestein in die
zu erbohrende Bahn, bald suchte er mit lastender Masse das Gewölbe
einzudrücken, und bald ließ er wieder aus seinem Schoß mächtige kalte
und warme Quellen, wahre Bergbäche, in die mühsam gebauten Stollen
einbrechen, Vernichtung und Untergang drohend.
„Bis zum November 1903 sollte nach der ursprünglichen
Berechnung der Tunnel erbohrt sein. Nach den Fortschritten der ersten
Zeit glaubte man den Durchschlag noch früher ermöglichen zu können.
Als man jedoch auf der Nordseite beim sechsten Kilometer angelangt
war, stieg plötzlich die Gesteinswärme in erschreckender und ganz
ungeahnter Weise. Für den siebenten Kilometer hatte man auf 36-37
Grad gerechnet; statt dessen fand man aber 45-56 Grad; 500 Meter
weiter waren es bereits 53 Grad, und immer noch schien die Hitze sich
steigern zu wollen. Die bloße Zuführung kalter Luft genügte nicht mehr,
um die weiteren Bohrarbeiten zu ermöglichen; es mußten besondere
Vorrichtungen aufgestellt werden, die durch mächtige Sprühregen von
eisigkaltem Wasser die Luft vor Ort so weit abkühlten, daß die Arbeit
wieder aufgenommen und fortgesetzt werden konnte.
„War es im Nordstollen die Hitze, so waren es im Süden das
nachdrückende Gestein und die gewaltigen Wassereinbrüche, welche
die Arbeiten fast völlig zum Stillstand brachten. Der Druck des Bergs
war ungeheuer; er zersplitterte die stärksten eingebauten Holzstämme
und verbog mächtige Eisenbalken. Erst durch den Einbau gewaltiger
Zementblöcke und stärkster Eisenträger gelang es, der fürchterlich
lastenden Wucht dauernden Widerstand zu leisten. Die einbrechenden
kalten und warmen Quellen, die den Tunnel überschwemmten, mußten
mit unendlicher Mühe gefaßt und abgeleitet werden. Durch die Spalten
des Gesteins rinnen jetzt ungefähr 1000 Sekundenliter ins Gewölbe und
durch den Parallelstollen ins Freie.
„Das Maximum des Arbeiterstands zeigte die Ziffer von 4000 Mann.
Weit über eine Million Kubikmeter Ausbruchsmaterial mußte aus dem
Berginnern ins Freie geschafft werden. Zu den Sprengungen wurden
etwa 1350 Tonnen Dynamit verwendet; dazu kamen etwa 4 Millionen
Sprengkapseln und ungefähr 5300 Kilometer Zündschnüre. Die Anzahl
der erforderlichen Bohrlöcher betrug rund 4 Millionen.“
Der stärkste der Wassereinbrüche, der plötzlich einsetzte, begrub
eine Anzahl von Arbeitern im nachstürzenden Gestein. An der Stelle, wo
sie gestorben sind, liegen sie noch heute im steinernen Ehrengrab, über
dem sich als das mächtigste aller Denkmäler die gewaltige Masse des
Simplon hoch emporwölbt.

13. Der stählerne Pfad

Tack! Tack! Tack! machen die Räder unseres nach Halle fahrenden
Schnellzugs.
Es ist ein eintöniges, in gleichen Abständen immer wiederkehrendes
Geräusch, das seltsam einschläfernd auf die Nerven wirkt. Die
Gleichmäßigkeit dieses ewig klingenden Tons weckt die Erinnerung an
manche gern gehörte Weise; während der auf seinen Federn sich
schaukelnde Wagen uns langsam einwiegt, scheint es einem jeden, als
sängen die Räder sein Lieblingslied.
Der Zug fliegt über den blanken, stählernen Pfad, über die
Schienen, wie man einfach sagt. Nichts scheint leichter als die
Ausstreckung der vier silberigen Stränge vor der Maschine. Und doch ist
die Arbeit von vielen Geschlechtern, die angestrengte Tätigkeit
unzähliger Geister notwendig gewesen, um nur den heutigen Zustand
zu erreichen, der von Vollkommenheit noch weit entfernt ist.
Die Unterlage für die Fahrbahn haben wir bereits besprochen. Es
bleibt uns übrig, Bettung, Schwellen, Schienen und das zugehörige
Kleineisenzeug in den Arten und Formen, wie sie heutzutage
angewendet werden, erst im einzelnen, dann in ihrem Zusammenhang,
also den O b e r b a u zu betrachten. Es ist ein weites Feld, wie Effi
Briests Vater in Fontanes Roman zu sagen pflegt.
Wir wissen aus Abschnitt 5, daß es die Aufgabe der Bettung ist, für
die Schwellen einen Lagerbezirk zu schaffen, in dem diese fest und
möglichst trocken liegen. Der Bettungsstoff muß daher Wasser sehr
leicht durchlassen und doch fest genug sein, um die sehr großen Kräfte,
die von oben und von den Seiten her gegen die Schienen und Schwellen
wirken, aufnehmen und über eine weite Fläche verteilen zu können.
Außerdem muß die Form der einzelnen Bettungsstücke so beschaffen
sein, daß man sie leicht unter die Schwellen schlagen kann, um deren
durch den Betrieb immer wieder bewirkte Senkung auszugleichen.
Die deutschen Bahnen sind entweder in Kies oder in Steinschlag
verlegt. Die tiefste Lage der Bettung auf dem Unterbau, die nur zu
tragen, aber keine seitlichen Kräfte aufzunehmen hat, wird auch öfter
aus gut zusammengesetzten, größeren Steinen, der sogenannten
Packlage, gebildet. Der Steinschlag besteht bei uns zumeist aus Basalt,
Porphyr, Quarzit oder Grauwacke und zwar in Form von scharfkantigen
kleinen Stücken mit einer Seitenlänge von drei bis vier Zentimetern.
Die Längsschwellen, mit denen der Eisenbahnoberbau einst
begann, sind heute als überlebt zu betrachten. Der Querschwellenbau
herrscht vor. Er wird aus hölzernen oder eisernen Stücken
zusammengesetzt, neuerdings hat man auch Versuche mit Schwellen
aus Beton mit Eiseneinlage gemacht. Auch die Schwellenschiene, das
heißt eine Schiene mit sehr breit ausladendem Fuß, der die Schwelle
ersetzt, kommt vor, jedoch nur selten und meist in Nebengeleisen.
Die Bevorzugung des Querschwellengleises ist leicht begreiflich
durch die großen Vorteile, die es bietet: die sichere Festhaltung der
Spur ohne besondere Vorkehrungen und die leichte Möglichkeit des
Erneuerns einzelner Stücke. Bei dieser Bauart kann man auch in
einfacher Weise eine Verstärkung der Tragfähigkeit des Gleises
bewirken, da man in solchem Fall nur nötig hat, die Zahl der Schwellen
für die Längeneinheit zu erhöhen.
Auf den preußischen Bahnen, deren Verhältnisse auch hier wieder
als Beispiel herangezogen werden sollen, ist der Querschnitt der
Schwellen stets ein Rechteck, meist mit abgeschrägten Kanten an der
oberen Fläche. Bei den Holzschwellen, die wir nun zunächst betrachten,
entstehen diese sogenannten Waldkanten, die man aus Gründen der
Holzersparung zuläßt,
meist von selbst; sie
ergeben sich für viele
Schwellen durch die Art,
wie diese aus dem vollen
Baumstamm
herausgeschnitten
werden. Die beiden
Schwellen oben und
unten auf Bild 112
können keinen voll
rechteckigen Querschnitt
mehr erhalten.
Die üblichen
Abmessungen für die
Schwellen sind: Breite 26
Zentimeter, Höhe 16
Zentimeter, Länge 2,70 Nach Haarmann: „Das Eisenbahngeleise“
Meter. Eine Bearbeitung 112. W i e H o l z s c h w e l l e n a u s e i n e m
der Oberfläche findet Stamm geschnitten werden
heute für gewöhnlich
nicht mehr statt, da die seitliche Neigung der Schienen durch
Zwischenlegen von Unterlagsplatten hergestellt wird. Die Löcher, welche
später die Befestigungsmittel für die Schienen, Nägel oder Schrauben,
aufzunehmen haben, werden vor dem Verlegen auf einer Seite
vorgebohrt, auf der anderen Seite geschieht das Bohren erst während
des Auslegens, damit man imstande ist, die häufig vorkommenden,
kleinen Abweichungen von der Regelspur auszuführen.
Bei uns werden in der Hauptsache Eiche, Buche, Fichte, Tanne und
Kiefer, diese letzte in größter Zahl, zu Schwellen verarbeitet. Unter ihnen
ist seltsamerweise das Buchenholz, obgleich es zu den sonst besonders
widerstandsfähigen Harthölzern gehört, am leichtesten vergänglich. Die
Buchenschwellen faulen so rasch, daß sie ohne die Anwendung
besonderer Erhaltungsverfahren gar nicht verwendet werden können.
Da es durch dieses Verfahren gelungen ist, auch die Weichhölzer sehr
haltbar zu machen, so geht der Verbrauch der teuren Eiche allmählich
immer weiter zurück. In neuerer Zeit wird die Brauchbarkeit der
Weichholzschwellen auch dadurch erhöht, daß man die Nägel und
Schrauben nicht mehr unmittelbar in ihren Körper einsetzt, sondern an
den in Betracht kommenden Stellen zunächst sehr starke, in der Mitte
durchbohrte Bolzen aus Hartholz einschraubt. Diese Dübel erst nehmen
die eisernen Befestigungsmittel auf.

113. H a r t h o l z v e r d ü b e l u n g
Verstärkung von Weichholzschwellen durch Einschrauben von
Hartholzdübeln zur Aufnahme der Schraubenlöcher

Die Holzschwellen verderben im natürlichen Zustand deshalb leicht,


weil der Holzsaft Eiweiß und andere Stoffe enthält, die sich im toten
Holz zersetzen und das Gefüge locker machen. Ferner ist die Schwelle
der Gefahr des Faulens so stark wie kaum ein anderer Baustoff gleicher
Art ausgesetzt, da Trockenheit und Feuchtigkeit im Bahnbett
unaufhörlich miteinander abwechseln. Man macht die Schwellen
standhaft gegen diese schweren Angriffe, indem man sie mit fremden
Stoffen vollkommen durchtränkt. Durch besondere Verfahren wird der
Holzsaft ausgesogen, und an seine Stelle werden unter sehr kräftigem
Druck Kreosot, Chlorzink oder kreosothaltiges Teeröl zwischen die
Fasern gepreßt. Die Lebensdauer der Schwellen steigt dadurch sehr
bedeutend. Eichenholz hält roh 14 bis 16 Jahre, getränkt 20 Jahre; bei
Buchenholz ist der Unterschied sehr viel größer, nämlich 3 Jahre gegen
12-18. Die Zahlen für Kiefernholz lauten 7-8 Jahre gegen 14-18. Die
Einführung des Tränkens bedeutet also eine außerordentlich große
Ersparnis bei der Unterhaltung des Gleisoberbaus und dies um so mehr,
als man die Beobachtung gemacht haben will, daß das Tränken die
Schwellen auch widerstandsfähiger gegen äußere Angriffe macht.

114. L a g e d e r E i s e n s c h w e l l e i n d e r B e t t u n g

Es wurde in dem Abschnitt über die Geschichte des Gleises bereits


kurz angedeutet, daß die eisernen Schwellen erst brauchbar wurden,
nachdem man ihnen eine vollkommen geschlossene, trogförmige
Gestalt gegeben hatte. Sie sind dadurch imstande, einen großen Teil der
Bettung vollkommen zu umgreifen und sich gegen jede Verschiebung zu
sichern, indem sie diesen Bettungsteil zwingen, sich bei Bewegungen
auf der darunter liegenden Fläche zu reiben. Die Eisenschwellen werden
heute sämtlich aus Flußeisen oder Flußstahl gewalzt. Die am meisten
gebräuchlichen Formen zeigt unser Bild 115; die Kreuzschwelle wird
jedoch immer seltener verwendet. Damit man die Befestigungsmittel für
die Schienen durch die Eisenschwellen hindurchstecken kann, müssen
diese an der Decke durchlocht werden. (Siehe auch Bild 52 auf Seite
78.)
Ausschlaggebend für die Stärke des Oberbaus ist die
Schwellenteilung, das heißt der im allgemeinen stets gleichmäßige
Abstand der einen Schwellenmitte von der anderen. Bei stark
befahrenen Hauptbahnen pflegen in Preußen auf einem Kilometer 1675
Schwellen zu liegen. Nur am Stoß werden die Schwellen näher
zusammengelegt, als der gewöhnliche Abstand beträgt. Auch die drei
nächsten Schwellen werden noch etwas herangerückt. Bei
Eisenschwellen bildet man am Stoß eine zusammenhängende
Doppelschwelle aus.
115. Q u e r s c h n i t t e v o n E i s e n s c h w e l l e n

Alle die bisher erwähnten Vorkehrungen im Unterbau und Oberbau


haben doch zuletzt nur den Zweck, die Schienen unverrückbar
festzuhalten. Diese selbst werden heute ausschließlich aus Flußstahl
bereitet. Zur Herstellung dieses Stoffs wird das aus dem Hochofen
gewonnene Roheisen im Siemens-Martin-Ofen oder in der Thomasbirne
von dem zu starken Kohlenstoffgehalt befreit. Es ist ein prächtiges
Schauspiel, dem Arbeiten von Thomasbirnen in einem großen Eisenwerk
zuzuschauen. In seinem Buch „Das Reich der Kraft“ schreibt der
Verfasser über die Eindrücke, die er bei dem Besuch einer
Schienenfabrik empfing:
Die unter dem hochgewölbten Dach einer großen Halle
aufgehängten Birnen für die Stahlbereitung werden von außen nicht
geheizt. Denn das Eisen wird in flüssigem Zustand eingefüllt und
Preßluft hindurchgedrückt, so daß drinnen eine rasende Glut entsteht.
Von Zeit zu Zeit räuspert sich eines der Ungeheuer und bläst einen
Klumpen flüssigen Feuers hinaus, der, von einem Funkenregen
begleitet, dumpf zur Erde niederfällt. Dann schlägt die Lohe mit
erneuter Kraft aus dem glühenden Maul und ein rollendes Geräusch
dringt hervor.
Wenn der Vulkan dort drinnen ein paar Stunden lang getobt hat,
wird durch elektrische Kraft ein großer Bottich hinzugefahren. Mit einem
plötzlichen Ruck senkt das flammengekrönte Haupt sich abwärts, und
das Ungeheuer speit seine ganze Flammenseele aus. Weithin wird alles
von einem blendenden Licht übergossen. Eine schwere, breite, mächtig
flutende Feuerwelle gleitet in den Bottich, ein Schwarm blendend weißer
Funkensterne fliegt weit hinaus. Minutenlang rinnt das Feuer in
kräftigem Strom und verbreitet eine kaum zu ertragende Hitze, ein
Licht, heller als tausend Bogenlampen. Dann endlich hört die ungeheure
Birne auf zu speien und zu brausen, richtet sich langsam und stolz
wieder in die Höhe, und der mit dem feuerflüssigen Eisen bis an den
Rand gefüllte Bottich fährt, ächzend unter seiner Last, davon. Sein
Inhalt wird in eiserne Gefäße gegossen; es entstehen mehrere
Walzblöcke, die darauf von kleinen Lokomotiven auf einer
Feldeisenbahn dem großen Kran in der Walzhalle zugeführt werden.
Wir folgen solch einem Block, aus dessen Leib Eisenbahnschienen
hergestellt werden sollen, auf seinem Weg und haben nun Gelegenheit,
einem Vorgang beizuwohnen, der an Pracht und Großartigkeit von
wenigen auf Erden übertroffen wird.
Im Sonnenglanz dunkelt die mächtige, nach allen Seiten hin weit
geöffnete Halle. Unter dem großen Wellblechdach ist alles Leuchten des
Tags erloschen. Man steht in einer silbergrauen Wolke, die leicht auf
und ab wallt und den Blick einschließt. Doch das Auge gewöhnt sich
rasch an den feinen Nebel und vermag ihn zu durchdringen.

116. E i s e r n e D o p p e l s c h w e l l e f ü r
Stoßunterstützung

Menschen mit ledernen Panzern, große spitze Eisenstangen,


abenteuerlich geformte Zangen gleich Waffen in den Händen, bewegen
sich lautlos und mit seltsamen Gebärden um ein hochragendes
schwarzes Gerüst, das in erhabener Größe dasteht.
Ein dumpfes Rollen ertönt.
Langsam heranbewegt, erscheint hoch droben, dicht unter dem
Hallendach, der glühende, funkensprühende Eisenblock. Der Kran, der
ihn vom Wagen genommen hat, fährt leicht auf hochliegendem Gleis;
sein Gerüst biegt sich nicht unter der Last der zweitausend Kilogramm.
Der Block ist dunkelrot. Man merkt, daß sein Bau, der eben erst aus
flüssigem Eisen gefügt wurde, sich noch nicht bei sich selbst zu Hause
fühlt. Knisternd springen Funken auf, hier und da zischt eine kleine
Feuergarbe an ihm empor. Wechselnde Farbenschattierungen laufen
über die Eisenmasse. Es ist als fröre sie in der kalten Welt; man könnte
denken, der mächtige Klotz atme. Eine ungeheure Glut entströmt ihm.
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!

ebookultra.com

You might also like