100% found this document useful (1 vote)
35 views

Mathematical Methods Using Python Applications In Physics And Engineering Vasilis Pagonis Christopher W Kulp download

The document is a textbook titled 'Mathematical Methods Using Python Applications in Physics and Engineering' by Vasilis Pagonis and Christopher W. Kulp, aimed at advanced undergraduate students. It integrates Python programming with mathematical methods, covering topics such as differentiation, integration, and differential equations, and includes practical coding examples. The book also features a dedicated GitHub website for code access and a solutions manual for instructors.

Uploaded by

ahedodiker6t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
35 views

Mathematical Methods Using Python Applications In Physics And Engineering Vasilis Pagonis Christopher W Kulp download

The document is a textbook titled 'Mathematical Methods Using Python Applications in Physics and Engineering' by Vasilis Pagonis and Christopher W. Kulp, aimed at advanced undergraduate students. It integrates Python programming with mathematical methods, covering topics such as differentiation, integration, and differential equations, and includes practical coding examples. The book also features a dedicated GitHub website for code access and a solutions manual for instructors.

Uploaded by

ahedodiker6t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Mathematical Methods Using Python Applications

In Physics And Engineering Vasilis Pagonis


Christopher W Kulp download

https://ebookbell.com/product/mathematical-methods-using-python-
applications-in-physics-and-engineering-vasilis-pagonis-
christopher-w-kulp-56163078

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Mathematical Methods Using Mathematica For Students Of Physics And


Related Fields Sadri Hassani

https://ebookbell.com/product/mathematical-methods-using-mathematica-
for-students-of-physics-and-related-fields-sadri-hassani-4124426

Mathematical Concepts And Methods In Modern Biology Using Modern


Discrete Models Raina Robeva And Terrell Hodge Eds

https://ebookbell.com/product/mathematical-concepts-and-methods-in-
modern-biology-using-modern-discrete-models-raina-robeva-and-terrell-
hodge-eds-4409990

Mathematical Modelling Of Decision Problems Using The Simus Method For


Complex Scenarios 1st Edition Nolberto Munier

https://ebookbell.com/product/mathematical-modelling-of-decision-
problems-using-the-simus-method-for-complex-scenarios-1st-edition-
nolberto-munier-35167640

Continuum Mechanics Using Mathematica Fundamentals Methods And


Applications Antonio Romano

https://ebookbell.com/product/continuum-mechanics-using-mathematica-
fundamentals-methods-and-applications-antonio-romano-36529658
Numerical And Analytical Methods For Scientists And Engineers Using
Mathematica Daniel Dubin

https://ebookbell.com/product/numerical-and-analytical-methods-for-
scientists-and-engineers-using-mathematica-daniel-dubin-2217562

Analytic Methods In Sports Using Mathematics And Statistics To


Understand Data From Baseball Football 2nd Edition 2nd Severini

https://ebookbell.com/product/analytic-methods-in-sports-using-
mathematics-and-statistics-to-understand-data-from-baseball-
football-2nd-edition-2nd-severini-56283544

Analytic Methods In Sports Using Mathematics And Statistics To


Understand Data From Baseball Football Basketball And Other Sports
Thomas A Severini

https://ebookbell.com/product/analytic-methods-in-sports-using-
mathematics-and-statistics-to-understand-data-from-baseball-football-
basketball-and-other-sports-thomas-a-severini-4726278

Practical Methods For Optimal Control Using Nonlinear Programming 1st


John T Betts

https://ebookbell.com/product/practical-methods-for-optimal-control-
using-nonlinear-programming-1st-john-t-betts-1375082

Mathematical Methods And Economic Theory Anjan Mukherji Subrata Guha

https://ebookbell.com/product/mathematical-methods-and-economic-
theory-anjan-mukherji-subrata-guha-46076142
Mathematical Methods
using Python
This advanced undergraduate textbook presents a new approach to teaching mathematical methods for sci-
entists and engineers. It provides a practical, pedagogical introduction to utilizing Python in Mathematical
and Computational Methods courses. Both analytical and computational examples are integrated from its
start. Each chapter concludes with a set of problems designed to help students hone their skills in mathemat-
ical techniques, computer programming, and numerical analysis. The book places less emphasis on math-
ematical proofs, and more emphasis on how to use computers for both symbolic and numerical calculations.
It contains 182 extensively documented coding examples, based on topics that students will encounter in
their advanced courses in Mechanics, Electronics, Optics, Electromagnetism, Quantum Mechanics etc.

An introductory chapter gives students a crash course in Python programming and the most often used
libraries (SymPy, NumPy, SciPy, Matplotlib). This is followed by chapters dedicated to differentiation, inte-
gration, vectors and multiple integration techniques. The next group of chapters covers complex numbers,
matrices, vector analysis and vector spaces. Extensive chapters cover ordinary and partial differential equa-
tions, followed by chapters on nonlinear systems and on the analysis of experimental data using linear and
nonlinear regression techniques, Fourier transforms, binomial and Gaussian distributions. The book is
accompanied by a dedicated GitHub website, which contains all codes from the book in the form of ready
to run Jupyter notebooks. A detailed solutions manual is also available for instructors using the textbook
in their courses.
Key Features:
• A unique teaching approach which merges mathematical methods and the Python programming skills
which physicists and engineering students need in their courses.
• Uses examples and models from physical and engineering systems, to motivate the mathematics being
taught.
• Students learn to solve scientific problems in three different ways: traditional pen-and-paper methods,
using scientific numerical techniques with NumPy and SciPy, and using Symbolic Python (SymPy).

Vasilis Pagonis is Professor of Physics Emeritus at McDaniel College, Maryland, USA. His research area is
applications of thermally and optically stimulated luminescence. He taught courses in mathematical phys-
ics, classical and quantum mechanics, analog and digital electronics and numerous general science courses.
Dr. Pagonis’ resume lists more than 200 peer-reviewed publications in international journals. He is cur-
rently associate editor of the journal Radiation Measurements. He is co-author with Christopher Kulp of
the undergraduate textbook “Classical Mechanics: a computational approach, with examples in Python
and Mathematica” (CRC Press, 2020). He has also co-authored four graduate level textbooks in the field
of luminescence dosimetry, and most recently published the book “Luminescence Signal analysis using
Python” (Springer, 2022).

Christopher Kulp is the John P. Graham Teaching Professor of Physics at Lycoming College. He has been
teaching undergraduate physics at all levels for 20 years. Dr. Kulp’s research focuses on modelling complex
systems, time series analysis, and machine learning. He has published 30 peer-reviewed papers in inter-
national journals, many of which include student co-authors. He is also co-author of the undergraduate
textbook “Classical Mechanics: a computational approach, with examples in Python and Mathematica”
(CRC Press, 2020).
Taylor & Francis
Taylor & Francis Group
http://taylorandfrancis.com
Mathematical Methods
using Python
Applications in Physics and Engineering

Vasilis Pagonis and Christopher W. Kulp


Designed cover image: Vasilis Pagonis

First edition published 2024


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
© 2024 Vasilis Pagonis and Christopher W. Kulp
Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot as-
sume responsibility for the validity of all materials or the consequences 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, mi-
crofilming, and recording, 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 trademarks and are used only for iden-
tification and explanation without intent to infringe.

Library of Congress Cataloging-in-Publication Data

Names: Pagonis, Vasilis, author. | Kulp, Christopher W., author.


Title: Mathematical physics using Python : applications in physics and
engineering / Vasilis Pagonis and Christopher W. Kulp.
Description: First edition. | Boca Raton : CRC Press, 2024. | Includes
bibliographical references and index.
Identifiers: LCCN 2023052970 | ISBN 9781032278360 (hbk) | ISBN
9781032278384 (pbk) | ISBN 9781003294320 (ebk)
Subjects: LCSH: Mathematical physics--Data processing--Textbooks. | Python
(Computer program language)--Textbooks.
Classification: LCC QC20.7.E4 P34 2024 | DDC
530.15/02855133--dc23/eng/20240209
LC record available at https://lccn.loc.gov/2023052970

ISBN: 978-1-032-27836-0 (hbk)


ISBN: 978-1-032-27838-4 (pbk)
ISBN: 978-1-003-29432-0 (ebk)

DOI: 10.1201/9781003294320

Typeset in Latin Modern font


by KnowledgeWorks Global Ltd.

Publisher’s note: This book has been prepared from camera-ready copy provided by the authors.
Dedication

The authors dedicate this book to their students


at McDaniel College and Lycoming College.
Taylor & Francis
Taylor & Francis Group
http://taylorandfrancis.com
Contents

Preface ........................................................................................................................... xiii

Chapter 1 Introduction to Python ............................................................................... 1


1.1 Data Types and Variables in Python ................................................ 1
1.2 Sequences in Python ......................................................................... 3
1.2.1 Lists ..................................................................................... 4
1.2.2 Range Sequences and List Comprehensions......................... 7
1.2.3 Tuple Sequences ................................................................... 9
1.2.4 Functions on Sequences........................................................ 9
1.3 Functions, for Loops and Conditional Statements ............................ 9
1.4 Importing Python Libraries and Packages ...................................... 13
1.5 The NumPy Library........................................................................ 14
1.5.1 Creating NumPy Arrays .................................................... 14
1.5.2 Array Functions, Attributes and Methods......................... 16
1.5.3 Arithmetic Operations with NumPy Arrays...................... 18
1.5.4 Indexing and Slicing of NumPy Arrays ............................. 21
1.6 The Matplotlib Module ................................................................... 22
1.6.1 2D Plots Using Matplotlib................................................. 23
1.6.2 3D Plots Using Matplotlib................................................. 25
1.7 Symbolic Computation with SymPy ............................................... 26
1.8 The lambdify() Function in Python ................................................ 28
1.9 End of Chapter Problems................................................................ 29

Chapter 2 Differentiation ........................................................................................... 34


2.1 Derivatives of Single-Variable Functions ......................................... 34
2.1.1 Rules for Differentiation..................................................... 35
2.2 Differentiating Analytical Functions in Python .............................. 39
2.3 A Detailed Example: Derivation of Wien’s Displacement Law ....... 47
2.4 Derivatives of Multivariable Functions............................................ 50
2.4.1 Introduction to Partial Differentiation............................... 50
2.4.2 Total Differentials .............................................................. 52
2.4.3 Total Derivative of a Function - The Chain Rule
Revisited ............................................................................ 54
2.4.4 Maximum and Minimum Problems.................................... 56
2.5 Power Series Approximations of Functions ..................................... 58
2.6 Numerical Evaluation of Derivatives ............................................... 63
2.7 End of Chapter Problems................................................................ 66

Chapter 3 Integration ................................................................................................ 70


3.1 Integrals .......................................................................................... 70
3.2 Review of Elementary Integrals ...................................................... 71
3.3 Overview of Integration Methods in Python................................... 72
3.4 Integration by Parts ........................................................................ 73
3.5 Parametric Integration for Definite Integrals .................................. 75

vii
viii Contents

3.6 Integrating Analytical Functions in Python.................................... 77


3.7 Fourier Series................................................................................... 80
3.8 Improper Integrals and Integrals of Special Functions .................... 82
3.9 Integrating Functions Defined by NumPy Arrays ........................... 88
3.9.1 Simpson’s Rule................................................................... 90
3.10 End of Chapter Problems................................................................ 91

Chapter 4 Vectors ...................................................................................................... 99


4.1 Vector Basics................................................................................... 99
4.2 Scalar and Vector Fields in Python ...............................................104
4.3 Vector Multiplication .....................................................................105
4.3.1 The Dot Product ..............................................................105
4.3.2 The Cross Product............................................................110
4.4 Triple Products ..............................................................................118
4.4.1 Triple Scalar Product........................................................118
4.4.2 Triple Vector Product .......................................................119
4.5 Non-Cartesian Coordinates ............................................................121
4.5.1 Polar Coordinates .............................................................121
4.5.2 Cylindrical Coordinates ....................................................124
4.5.3 Spherical Coordinates .......................................................128
4.6 Differentiation of Vectors ...............................................................131
4.7 Parametric Equations of Lines and Planes.....................................135
4.8 End of Chapter Problems...............................................................143

Chapter 5 Multiple Integrals.....................................................................................147


5.1 Multiple Integrals ...........................................................................147
5.2 Evaluation of Double Integrals.......................................................151
5.2.1 The Evaluation of Double Integrals Over a Rectangular
Domain .............................................................................151
5.2.2 The Evaluation of Double Integrals Over a
Non-Rectangular Domain .................................................153
5.3 Evaluation of Triple Integrals.........................................................156
5.4 Change of Variables in Multiple Integrals ......................................159
5.4.1 Using Polar Coordinates ...................................................159
5.4.2 Using Cylindrical Coordinates ..........................................161
5.4.3 Using Spherical Coordinates .............................................163
5.5 Application of Multiple Integrals: Moment of Inertia Tensor ........165
5.5.1 Numerical Evaluation of Multiple Integrals ......................168
5.6 End of Chapter Problems...............................................................171

Chapter 6 Complex Numbers....................................................................................176


6.1 The Complex Plane........................................................................176
6.2 Trigonometric Functions and Complex Exponentials.....................179
6.3 Arithmetic with Complex Numbers ...............................................184
6.4 Application of Complex Numbers in AC Circuits ..........................186
6.5 Equations with Complex Numbers.................................................190
6.6 Functions of a Complex Variable ...................................................193
6.6.1 Exponentials, Powers and Roots of Complex Numbers ....193
6.6.2 Hyperbolic Functions ........................................................196
6.7 Complex Vectors ............................................................................197
Contents ix

6.8 End of Chapter Problems...............................................................199

Chapter 7 Matrices ...................................................................................................203


7.1 The Structure of a Matrix..............................................................203
7.1.1 Defining Matrices in Python.............................................204
7.1.2 Vectors as Matrices ...........................................................205
7.2 Matrix Operations..........................................................................205
7.2.1 Matrix Equivalence ...........................................................205
7.2.2 Multiplication by a Scalar.................................................205
7.2.3 Matrix Addition ................................................................206
7.2.4 Matrix Multiplication .......................................................206
7.2.5 Trace of a Matrix ..............................................................208
7.2.6 Transpose and Hermitian Adjoint of a Matrix..................209
7.3 The Determinant............................................................................211
7.3.1 Calculating Determinants .................................................212
7.3.2 Determinants as Representations of Area and Volume .....214
7.3.3 The Jacobian Determinant and Volume
Transformations ................................................................216
7.4 Matrices and Systems of Linear Equations ....................................219
7.4.1 Representing Systems of Linear Equations as a Matrix
Equation ...........................................................................220
7.4.2 Representing Systems of Linear Equations as an
Augmented Matrix............................................................222
7.4.3 Homogeneous Equations ...................................................225
7.5 Matrices as Representations of Linear Operators...........................228
7.6 Eigenvalues and Eigenvectors.........................................................232
7.7 Diagonalization of a Matrix ...........................................................236
7.8 End of Chapter Problems...............................................................237

Chapter 8 Vector Analysis ........................................................................................243


8.1 Scalar and Vector Fields ................................................................243
8.2 The Gradient of a Scalar Field.......................................................246
8.2.1 The Gradient in Other Coordinate Systems .....................252
8.3 Properties of the Gradient .............................................................255
8.4 Divergence ......................................................................................256
8.5 Curl ................................................................................................259
8.6 Second Derivatives Using ∇ ...........................................................264
8.7 Line Integrals .................................................................................266
8.8 Conservative Fields ........................................................................271
8.9 Area Integrals and Flux .................................................................273
8.10 Green’s Theorem in the Plane........................................................277
8.11 The Divergence Theorem ...............................................................279
8.12 Stokes’s Theorem ...........................................................................281
8.13 End of Chapter Problems...............................................................284

Chapter 9 Vector Spaces ...........................................................................................288


9.1 Definition of a Vector Space...........................................................288
9.2 Finite Dimensional Vector Spaces ..................................................289
9.2.1 Linear Independence .........................................................289
9.2.2 Basis Vectors.....................................................................291
x Contents

9.2.3 Beyond Cartesian Coordinates..........................................291


9.2.4 The Gram-Schmidt Method..............................................292
9.3 Vector Spaces of Functions.............................................................293
9.3.1 Definition ..........................................................................294
9.3.2 Functions and Linear Independence..................................294
9.3.3 Inner Products and Functions...........................................295
9.3.4 Basis Functions .................................................................297
9.3.5 The Gram-Schmidt Method for Functions........................298
9.4 Infinite Dimensional Vector Spaces ................................................300
9.4.1 Quantum Mechanics and Hilbert Space............................300
9.5 End of Chapter Problems...............................................................302

Chapter 10 Ordinary Differential Equations...............................................................306


10.1 Definitions and Examples of Differential Equations.......................306
10.2 Separable Differential Equations ....................................................308
10.3 Symbolic Integration of Differential Equations Using SymPy........310
10.4 General Solution of First Order Linear ODEs: The Integrating
Factor Method................................................................................313
10.5 ODEs for Oscillating Systems: General Considerations.................315
10.6 The Simple Harmonic Oscillator ....................................................315
10.7 Numerical Integration of the ODE of a Simple Plane Pendulum...318
10.8 Damped Harmonic Oscillator.........................................................321
10.8.1 Case I: Overdamped Oscillations ......................................322
10.8.2 Case II: Underdamped Oscillations...................................323
10.8.3 Case III: Critically Damped Oscillations ..........................323
10.9 Forced Harmonic Oscillator............................................................326
10.10 The Principle of Linear Superposition ...........................................332
10.11 Electrical Circuits...........................................................................335
10.12 Phase Space....................................................................................337
10.13 Systems of Differential Equations ..................................................339
10.14 The Legendre Equation..................................................................345
10.14.1 Associated Legendre Functions .........................................349
10.15 The Bessel Equation ......................................................................354
10.16 End of Chapter Problems...............................................................361

Chapter 11 Partial Differential Equations ..................................................................366


11.1 Separation of Variables ..................................................................366
11.2 The Heat Equation.........................................................................367
11.2.1 The Product Solution to the One-Dimensional Heat
Equation ...........................................................................367
11.2.2 The Particular Solution of the Heat Equation:
The Cooling Process in a Uniform Rod ............................370
11.3 The Laplace Equation ....................................................................373
11.4 Application of the Laplace Equation in Electrostatics ...................376
11.5 The Wave Equation........................................................................379
11.6 Application of the Wave Equation for a Plucked String:
Traveling Waves .............................................................................381
11.7 The Laplace Equation in Cylindrical Coordinates .........................385
11.7.1 Application of the Laplace Equation: Electric Potential
Inside a Cylinder...............................................................387
Contents xi

11.8 The Laplace Equation in Spherical Coordinates ............................390


11.8.1 Application of the Laplace Equation: The Electric
Potential Due to a Charged Sphere ..................................391
11.9 General Outline for Solving Linear PDEs ......................................393
11.10 End of Chapter Problems...............................................................394

Chapter 12 Analysis of Nonlinear Systems .................................................................398


12.1 The Difference Between Linear and Nonlinear Systems .................398
12.2 Phase Portraits...............................................................................399
12.3 Fixed Points and Equilibria ...........................................................401
12.3.1 Finding Fixed Points ........................................................402
12.3.2 The Classification of Fixed Points ....................................403
12.4 Bifurcations of Fixed Points...........................................................407
12.5 The Phase Portrait, Revisited........................................................410
12.6 Nonlinear Oscillations and Limit Cycles ........................................417
12.7 Chaos .............................................................................................421
12.7.1 The Lorenz Equations.......................................................421
12.7.2 Sensitivity to Initial Conditions........................................425
12.7.3 Lyapunov Exponents and the Horizon Time ....................426
12.8 How to Analyze a Nonlinear System..............................................427
12.9 End of Chapter Problems...............................................................427

Chapter 13 Analysis of Experimental Data ................................................................434


13.1 Estimating Uncertainties................................................................434
13.2 Propagation of Uncertainties..........................................................437
13.3 Linear Regression and the Method of Least Squares .....................440
13.4 Data Transformations ....................................................................442
13.4.1 Feature Engineering ..........................................................442
13.4.2 Power Law Relationships and Log-Log Plots....................445
13.4.3 Exponential Relationships and Log-Linear (Semi-Log)
Plots..................................................................................447
13.5 Multivariate Linear Regression ......................................................449
13.6 Nonlinear Regression......................................................................452
13.7 Fourier Transforms .........................................................................454
13.8 Discrete Fourier transforms............................................................458
13.9 Discrete and Continuous Random Variables ..................................461
13.9.1 Discrete Random Variables...............................................461
13.9.2 Continuous Random Variables..........................................463
13.10 Useful Probability Functions..........................................................467
13.10.1 The Binomial Distribution................................................467
13.10.2 Normal Distribution..........................................................469
13.10.3 Poisson Distribution..........................................................471
13.11 End of Chapter Problems...............................................................473

Further Reading and Additional Resources...........................................................481

Index ..............................................................................................................................483
Taylor & Francis
Taylor & Francis Group
http://taylorandfrancis.com
Preface
A NEW APPROACH TO TEACHING MATHEMATICAL METHODS FOR
SCIENTISTS AND ENGINEERS
In our combined 57 years of experience teaching undergraduate courses, we have found that
computation should be front and center in a science education. Programming is a core
skill for scientists and engineers, that should be taught alongside advanced mathematical
methods. It is in this spirit that we created this textbook.
The use of computers to solve problems has become a fundamental and critical skill in all
scientific fields. This book merges instruction in mathematical methods and programming,
into a single presentation. In our approach, computer programming and computer algebra
systems are treated as simply one more tool for problem solving. Alongside instruction in
mathematical methods beyond calculus, we provide instruction in using computers to solve
science and engineering problems.
This textbook is intended for students who have had two semesters of calculus and are
pursuing degrees in science or engineering, where mathematics is used to solve problems
and to model physical systems. We created a book which
1. Provides an overview of the mathematics needed to pursue a degree in science and
engineering.
2. Shows students how to use Python to solve mathematical problems.
3. Uses examples and models from physical and engineering systems, to motivate the
mathematics being taught.
There are already excellent textbooks being used by instructors to teach mathematical
methods for scientists and engineers. For example, the textbook by Boas (Mathematical
methods in the physical sciences, Wiley, 2005), is a classic comprehensive mathematical
methods textbook, which has been used for many years in universities and colleges. How-
ever, there is a lack of undergraduate textbooks in which programming is taught alongside
the mathematical methods. We believe that this textbook fills this gap in the literature,
by providing a unique teaching approach for both the mathematics and the programming
skills which students will need upon graduation.
We chose Python because of its popularity and open source nature. Using Python
to perform mathematical calculations is a transferable skill students will find valuable,
regardless of what they choose to do with their degree. This book is as much about learning
to use Python to solve problems, as it is about learning mathematics. Writing a book
intimately tied to a language runs the risk of becoming out of date when the language is
updated. However most of the Python commands chosen in this book have been around
a long time and are widely used by scientists and engineers. Students who have worked
through this book should be comfortable adapting to changes in the Python language as
they arise.

TO THE INSTRUCTORS
This textbook can be used for a Mathematical Methods course, or for any course where
students need to learn advanced mathematics as well as programming techniques.
It is important for students to see the applications for the mathematics they are learning.
In all chapters, we motivate the mathematics with examples from science or engineering.

xiii
xiv Preface

The Python examples in this book cover topics students will encounter in their advanced
courses in Mechanics, Electronics, Optics, Electromagnetism, Quantum Mechanics etc. The
end of chapter problems are also chosen with these advanced courses in mind.
Asking students to learn both mathematics and a computer programming language can
be a daunting task. Chapter 1 of this textbook gives students a crash course in Python
programming and the most often used libraries (SymPy, NumPy, SciPy, Matplotlib). In-
structors can use Chapter 1 as an assigned reading, teach the material like any other chapter,
or skip it and have students learn the code as they work through the mathematics. This
introductory material is followed by chapters dedicated to differentiation, integration, vec-
tors and multiple integration techniques. In the next group of chapters we cover complex
numbers, matrices, vector analysis and provide an introduction to vector spaces. Exten-
sive chapters cover ordinary and partial differential equations, followed by a chapter on
the analysis of nonlinear systems. Finally, a chapter on the analysis of experimental data
introduces students to linear and nonlinear regression techniques, Fourier transforms and
Poisson, binomial and Gaussian distributions.
Students and instructors can download the open access codes used in all the chapters
of this book from the website https://github.com/vpagonis/CRCbook in the form of
ready-to-run Jupyter notebooks.
Our goal is for students to learn how to tackle a science problem, by using three com-
plementary and equally important approaches:

• Solve a problem using pen and pencil (the “by hand” approach)

• Use symbolic Python (SymPy) to carry out symbolic analytical calculations (the sym-
bolic approach)

• Use numerical and scientific Python (Numpy and SciPy) for problems requiring a
numerical approach (the numerical approach).
This is not a textbook for teaching numerical methods in science, since there are already
several very good textbooks covering numerical techniques. Our approach to numerical
solutions relies on the numerical integration libraries available in SciPy and NumPy.

TO THE STUDENTS
One of the goals of this book is to teach you how to use computational tools to solve
mathematical problems in sciences and engineering. This is an important transferable skill,
useful regardless of your career path.
We understand learning both mathematics and programming at the same time may
seem daunting. However, you can do it! Search engines and AI are your friend. If you
can’t remember how to do something in Python, it is okay to search online. For example, a
search of “How to solve a differential equation in Python” will result either in the website
for a particular Python library (such as SymPy), or to another site which demonstrates the
use of the necessary code. Over time, your coding skills will grow and you will find yourself
searching for the “simple” things less often.
A word of warning. Do not mindlessly copy and paste code you find online! To learn how
to use Python and other languages, it is critical that you write your own codes, and that
you understand how the codes are structured and organized. The mathematical methods
and the programming skills you will obtain from this book are very valuable skills, which
you can carry with you in all of your scientific education! If you simply copy and paste
code, you will be cheating yourself out of learning these skills.
Preface xv

ACKNOWLEDGMENTS
We want to thank several people who have helped make this book happen. We thank
Rebecca Davies and Danny Kielty at CRC Press and Kumar Shashi at KnowledgeWorks
Global, for all of their help in the preparation of this book. While working on this book, Dr
Kulp was supported by a Lycoming College Sabbatical Leave and Professional Development
Grant.
Taylor & Francis
Taylor & Francis Group
http://taylorandfrancis.com
1 Introduction to Python
In this introductory chapter, we present the basics of using Python, focusing on the most
frequently used libraries (SymPy, NumPy, SciPy, Matplotlib). We discuss the various data
types, variables and sequences, and give examples of functions, loops and conditional state-
ments. We show how to use functions and methods and how to work with NumPy arrays
using indexing and slicing. We introduce the Matplotlib library and how to set up 2D and
3D graphics. Finally, we give examples of symbolic evaluations using SymPy and how to
use the lambdify function in Python.

1.1 DATA TYPES AND VARIABLES IN PYTHON


The main numeric types in Python are integers, floating point numbers and complex num-
bers. A floating point number (or float) is a real number written in decimal form. Python
stores floats and integers internally in different ways. Python 3 automatically converts in-
teger to floats as needed. If you are working with an earlier version of Python, you may
need to be more careful when working with variables of different types.
In Example 1.1 we assign a value to a variable using the assignment operator =, for
example a = 0.0003 assigns the value of 0.0003 to the variable a. We can also define
variables by using scientific notation
√ to represent floats, for example b = 1.64e-4. Python
uses the letter j to represent −1, and the built-in function complex(a,b) creates the
complex number a+b*j. We can use the built-in function type() to identify the type of a
Python object, and the built-in function print(a) is used to print the value of a variable.
Similar to several other computer languages, the line e = ′ time′ defines a string variable e.
Example 1.1 shows how the function type(a) can be used to find out what class of
object the variable a belongs to. In most codes of this book, you will see the line of code
print(’-’*28,’CODE OUTPUT’,’-’*29)
This line produces a horizontal line labeled CODE OUTPUT and is used to separate
the Python code from the output generated by the code.

Example 1.1: Variable types in Python

Assign Python variables to each of the quantities 0.00007, 1.64e-4, 10, 3+4i, time. Use the
Python function type(a) to determine what type of variable each of these quantities represents.

Solution:

a = 0.00007 #define variables


b = 1.64e-4
c = 10
d = complex(3,4)
e = 'time'

print('-'*28,'CODE OUTPUT','-'*29)

print('\nVariable a = 0.0003 belongs to type:',type(a))

DOI: 10.1201/9781003294320-1 1
2 Mathematical Methods using Python: Applications in Physics and Engineering

print('Variable b = 1.64e-4 belongs to type:',type(b))


print('Variable c = 10 belongs to type:',type(c),'\n')

print('A complex number created with complex(3,4)=',d)


print('Variable d = complex(3,4) belongs to type:',type(d),'\n')

print("Variable e = 'time' belongs to type:",type(e))

---------------------------- CODE OUTPUT -----------------------------

Variable a = 0.0003 belongs to type: <class 'float'>


Variable b = 1.64e-4 belongs to type: <class 'float'>
Variable c = 10 belongs to type: <class 'int'>

A complex number created with complex(3,4)= (3+4j)


Variable d = complex(3,4) belongs to type: <class 'complex'>

Variable e = 'time' belongs to type: <class 'str'>

Multiple variable assignments can be compressed to one line. For example, the code
a,b,c = 1, 2, 3 is a compressed version of the three individual lines of code a = 1, b =
2 and c = 3.
The common arithmetic operators in Python are addition +, subtraction −, multipli-
cation ∗, division / and exponentiation ∗∗. In addition, the % operator is used to find the
remainder (or modulo), and the // is used for integer division.
In Python we can use f-strings to format the printing of variables. Within the f-string,
any variable can be enclosed inside curly brackets; for example, print(f′ {a}′ ) will print the
numerical value of the variable a, and print(f′ {a**2}′ ) prints the numerical value of a2 .
By using the f-string formats print(f′ {a:.3}′ ), print(f′ {a:.2e}′ ), print(f′ {a:.2f}′ )
and print(f′ {a:g}′ ), we print the variable a using two decimals, using scientific notation,
and as a float in generic notation, respectively.
In Example 1.2 we use f-strings to format the printing of variables.

Example 1.2: Using f-strings to format Python output

Assign Python variables a, b to the numbers 5.0/3 and 1.645.


(a) Use f-strings to print the variable a using scientific notation with two significant figures.
(b) Print the variable a2 without any formatting and by using generic notation.
(c) Print the variable b using two decimal points in the output of the code.
(d) What does round(a,2) and round(b,1) produce in the code?

Solution:

a = 5.0/3 #define variables


b = 1.645

print('-'*28,'CODE OUTPUT','-'*29,'\n')
Introduction to Python 3

print(f'Without formatting, the variable a={a}','\n')


print(f'Using scientific notation, the variable a={a:.2e}')

print(f'Without formatting, the square of variable a is {a**2}')


print(f'Using generic notation, the square of variable a is \
{a**2:g}','\n')

print(f'Using two decimals, the variable b=1.645 is {b:.3}')

print('\nround(a,2) produces ',round(a,2))


print('round(b,1) produces ',round(b,1))

---------------------------- CODE OUTPUT -----------------------------

Without formatting, the variable a=1.6666666666666667

Using scientific notation, the variable a=1.67e+00


Without formatting, the square of variable a is 2.777777777777778
Using generic notation, the square of variable a is 2.77778

Using two decimals, the variable b=1.645 is 1.65

round(a,2) produces 1.67


round(b,1) produces 1.6

A variable name cannot begin with a number, and there are reserved words in Python
which should not be used as variables. Table 1.1 shows a partial list of reserved words in
Python.

Table 1.1
Partial list of reserved words in Python.

False None def elif True


class for from or if
finally lambda nonlocal else sum
return try and import min
is not del break max
continue sum global list array

1.2 SEQUENCES IN PYTHON


The main sequence types in Python are lists, tuples and range objects. The main differences
between these sequence objects are:
Lists are mutable; i.e. their elements can be modified and are usually homogeneous (i.e.
objects of the same type create a list of similar objects)
4 Mathematical Methods using Python: Applications in Physics and Engineering

Range objects are efficient sequences of integers (commonly used in loops). They use a
small amount of memory and yield items only when needed
Tuples are immutable; i.e. their elements cannot be modified, and their elements are
usually heterogeneous (i.e. objects of different types create a tuple, describing a
single structure)
In the next three subsections, we look at examples of these types of sequences.

1.2.1 LISTS
We create a Python list using square brackets, with items separated by commas. Lists can
contain data of any type and even other lists. For example
a=[2.0,[3,0],5j,[1,1,2],′ s′ ,1]
defines a list containing floats, integers, complex numbers, other lists and strings.
We can access the elements of a list by their index, and it is important to remember that
lists are indexed starting at 0, not at 1. For example, print(a[0]) prints the first element
in list a, and print(a[2]) prints the third element. We can also use negative indices to
access elements starting from the end of the list so that print(a[-1] prints the last element
in the list, print(a[-2]) prints the second to last element etc.
Since lists are mutable, they can be altered, so we can redefine any of the elements in
the list, for example a[-1] = -2 sets the last element of the list to −2. We can use multiple
indices to access several entries in a list of lists; for example, print(a[1][0]) will print the
first element in the element a[1]. In the above list a, the element print(a[1][0]) is 0.
We can define sub-lists called slices by using the syntax
a[start:end:step]
For example, the slice a[2:5:2] starts at index 2 and increases by a step of 2 taking every
second element in the list, but does not include the ending value 5 of the index. We can
omit one of the indices or the step parameter in a slice, for example a[:5] creates a list
of the first five elements of a, and a[2:] creates a list of all the elements of a after and
including a[2]. Likewise, a[::2] creates a list which contains every other element in a.
Lists can be concatenated using the addition operator +; for example; a[1]+a[3] creates
a new list with the elements from both a[1], a[3].
Example 1.3 presents how to use these general properties of lists and how to access and
modify parts of a list.

Example 1.3: Accessing and modifying list elements in Python

Consider the Python list


a = [2,[3,0],5,[1,1,2],′ s′ ,[1,4],2,5]
(a) Write a code to add the first and last element in this list.
(b) Modify the third element in the list so that it is equal to −2.
(c) What is the a[3][2] element of the list?
(d) Create a new list which starts from the third element in list a, and contains every third element
of a.
(e) Create a new list that contains the first five elements of a
(f) What does the code a[1]+a[3] produce?
(g) What does the code a[1]*3 produce?
Introduction to Python 5

Solution:
(a) The first and last element in this list are added by a[0]+a[-1]
(b)–(c) a[2]=-2 sets the third element in the list equal to −2. Similarly, a[3][2] obtains the
third part of the fourth element of the list.
(d)–(e) The line a[2:len(a):2] creates a new list which starts from the third element a[2] in
the list, up to the length of the list which is specified by len(a).
(f)–(g) The code a[1]+a[3] produces a new list by concatenating the list [1, 1, 2] to the end of
the list [3, 0]. Finally, a[1]*3 produces a new list by repeating the elements of list a[1] three
times.

print('-'*28,'CODE OUTPUT','-'*29,'\n')

a = [2,[3,0],5,[1,1,2],'s',[1,4],2,5] # define list a

print('list a=',a)

print('the sum of the first and last element is: ',a[0]+a[-1])

a[2] = -2
print('\na[2] = -2 modifies list a into \na =',a,'\n')

print('The a[3][2] element is =', a[3][2],'\n')


print('The a[2:len(a):2] sequence is =',a[2:len(a):2])
print('The a[:5] sequence is =',a[:5])

print('\nThe a[1]+a[3] sequence is =',a[1]+a[3])


print('The a[1]*3 sequence is =',a[1]*3)

---------------------------- CODE OUTPUT -----------------------------

list a= [2, [3, 0], 5, [1, 1, 2], 's', [1, 4], 2, 5]


the sum of the first and last element is: 7

a[2] = -2 modifies list a into


a = [2, [3, 0], -2, [1, 1, 2], 's', [1, 4], 2, 5]

The a[3][2] element is = 2

The a[2:len(a):2] sequence is = [-2, 's', 2]


The a[:5] sequence is = [2, [3, 0], -2, [1, 1, 2], 's']

The a[1]+a[3] sequence is = [3, 0, 1, 1, 2]


The a[1]*3 sequence is = [3, 0, 3, 0, 3, 0]

Individual elements can be assigned separate variables in a list. For example, a, b, c =


[1,2,3] stores the value of 1 in the variable a, the value of 2 in b, and the value of 3 in c.
This is sometimes referred to as unpacking a list.
Lists cannot be copied like numeric data types by using, for example a statement like b
= a. Specifically, a statement like b = a does not create a new list b from list a, but simply
makes a reference to a. By setting a[0] = 1, this automatically sets also the first element
of list b to 1. In other words, if we use the statement b = a and then modify any value in
list a, the change will also be visible in list b.
6 Mathematical Methods using Python: Applications in Physics and Engineering

This confusion can be avoided by using the b = a.copy() command, which creates two
isolated objects whose contents share the same reference. This is referred to as shallow
copying of an object.
One can also use the b = copy.deepcopy(a) command, which creates two isolated
objects whose contents and structure are completely isolated from each other. This is
referred to as deep copying of an object. The deep copy is an independent copy of the
original object and all its nested objects. In other words, if we make changes to any nested
objects in the original object, we will see no changes to the deep copy.
Example 1.4 shows some of the differences between the shallow and deep copies of a list.

Example 1.4: Shallow and deep copies of objects

What does each of these groups of code produce in the output?

Example A:
c = [1,[2,3],4]
d = c
d[1] = 0
print(c,d)

Example B:
c = [1,[2,3],4]
d = c.copy()
d[1][1] = 0
print(c,d)

Example C:
c = [1,[2,3],4]
d = c.copy.deepcopy()
d[1][1] = 0
print(c,d)

Solution:
The comments in the code describe the result in each of the above codes. Note that this example
is the first time we use comments in our code. Any statement following a # is not executed
by the Python interpreter. Comments are useful to help a human reader of the code (including
yourself) understand what the program is doing. The value of comments cannot be overstated.

import copy
print('-'*28,'CODE OUTPUT','-'*29,'\n')

#Example A:
print('Example A: Effect of d = c statement')
c = [1,[2,3],4]
print('old_c = ',c)
d = c
d[1] = 0
print('d[1] = 0') # modifies both the shallow copy d and the original c
print('new_c = ',c,' new_d = ',d)

#Example B:
print('\nExample B: Shallow copy using d = c.copy(), modify inner element d[1][1]')
Introduction to Python 7

c = [1,[2,3],4]
print('old_c = ',c)
d = c.copy()
d[1][1] = 0
print('d[1][1] = 0') # modifies the shallow copy d, and the original c
print('new_c = ',c,' new_d = ',d)

#Example C:
print('\nExample C: Deep copy using copy.deepcopy(c), modify inner element d[1][1]')
c = [1,[2,3],4]
print('old_c = ',c)
d = copy.deepcopy(c)
d[1][1] = 0
print('d[1][1] = 0') # modifies the deep copy d, but not the original c
print('new_c = ',c,' new_d = ',d)

---------------------------- CODE OUTPUT -----------------------------

Example A: Effect of d = c statement


old_c = [1, [2, 3], 4]
d[1] = 0
new_c = [1, 0, 4] new_d = [1, 0, 4]

Example B: Shallow copy using d = c.copy(), modify inner element d[1][1]


old_c = [1, [2, 3], 4]
d[1][1] = 0
new_c = [1, [2, 0], 4] new_d = [1, [2, 0], 4]

Example C: Deep copy using copy.deepcopy(c), modify inner element d[1][1]


old_c = [1, [2, 3], 4]
d[1][1] = 0
new_c = [1, [2, 3], 4] new_d = [1, [2, 0], 4]

1.2.2 RANGE SEQUENCES AND LIST COMPREHENSIONS


The second important type of sequence in Python is a range object, created with the built-
in function range(a:b:step), where a, b and step are integers. This function creates an
object representing the sequence of integers from a to b (excluding b), incremented by the
variable step.
An important feature of Python that we use frequently in this book is a list comprehen-
sion, with the general syntax
[expression for item in sequence]
Here sequence is a sequence object (e.g. a range, a list, a tuple etc.), item is a variable
name which takes each value in the sequence and expression is a Python expression which
is calculated for each value of item. For example
[u**2 for u in [1,2,3]]
produces a new sequence with the squares of the integer sequence [1,2,3].
8 Mathematical Methods using Python: Applications in Physics and Engineering

As another example, we can use the remainder operator % to create a periodic sequence of
(0,1,2,3) and length 12 with the line of code:
[x%4 for x in range(0,12)]
Example 1.5 presents various properties of the range() function. Notice that when we
print a range object, this does not display the elements when printed. This is because a
range object yields values only when they are needed. However, the function list() can
convert a range object into a list object whose elements can then be printed. Example 1.5
also demonstrates list comprehensions.

Example 1.5: Using the range() function

(a) What does the line print(range(1,7,2)) produce in the output of the Python code?
(b) Change the object range(1,7,2) into a list by using the Python function list().
(c) Find the maximum element, the sum of the elements and the length of the object
range(1,7,2)
(d) What will be the result of the code [u**3 for u in [1,2,3]]
(e) What will be the result of the code [x%3 for x in range(0,12)]

Solution:
The comments in the code describe the result in each case.

print('-'*28,'CODE OUTPUT','-'*29,'\n')

a = range(1,7,2)
print('Define the range sequence a = ',a,'\n')
# print(a) does not print the elements of the range() object

# Use list(a) to convert the range into a list, then print elements
print('list(a) gives: ',list(a),'\n')

print('The length of the range sequence a is = ',len(a))


print('The sum of elements in the range sequence a is = ',sum(a))
print('The maximum of the range sequence a is = ',max(a))

c, d = [3,'s'] # unpacking a sequence


print("\nUnpack the sequence [3,'s'], to get: c = ",c,' d = ',d,'\n')

e = [u**3 for u in [1,2,3]] # a list comprehension


print('The list comprehension e = ',e)

f = [x%3 for x in range(0,12)] # another list comprehension


print('The list comprehension f = ',f,'\n')

---------------------------- CODE OUTPUT -----------------------------

Define the range sequence a = range(1, 7, 2)

list(a) gives: [1, 3, 5]

The length of the range sequence a is = 3


The sum of elements in the range sequence a is = 9
Introduction to Python 9

The maximum of the range sequence a is = 5

Unpack the sequence [3,'s'], to get: c = 3 d = s

The list comprehension e = [1, 8, 27]


The list comprehension f = [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]

1.2.3 TUPLE SEQUENCES


The third type of Python sequence is a tuple. We create a tuple by using parentheses instead
of square brackets. For example
a = (1,3,′ s′ )
The major difference between tuples and lists is that tuples are immutable, i.e. their
elements cannot be altered. However, the indexing, slicing and concatenating operations
for tuples are essentially the same as for lists. In this book we will be using list and range
objects in most examples and will occasionally encounter tuples.

1.2.4 FUNCTIONS ON SEQUENCES


Python has several built-in functions for computing with sequences. For example, len(a),
sum(a), max(a), min(a), evaluate the length, sum, maximum and minimum element in the
list. We can also sort the list using sorted(a). We also note a major difference between
string and list types in Python. Lists are mutable but strings are not, i.e. we can modify
the value of an element in a list, but not for a string. However, parts of a string can be
extracted using slices; for example, ′ hi′ [1] will extract the second letter in the string ′ hi′ .

1.3 FUNCTIONS, FOR LOOPS AND CONDITIONAL STATEMENTS


This section is a brief introduction to functions, for loops and conditional statements in
Python. We will demonstrate these over the next four examples. All programming lan-
guages have their own way of setting up functions, for loops and conditionals. Python uses
indentations and colons for these statements. In the next four examples, pay close attention
to how Python uses indentations and colons to delimit blocks of code. There should be no
extra white spaces in the beginning of any line, and the line before any indented block must
end with a colon character.
We begin with Example 1.6 where we wish to calculate the position of a particle starting
at the origin with initial speed v0 , moving under a constant acceleration a at a time t using:
1
y = v0 t + a t2 (1.3.1)
2
Because we wish to evaluate (1.3.1) several times in our code, we will define (1.3.1) as a
function in Python and we will use a for loop for our calculation.
The first three lines of code in Example 1.6 define the function f, by using the def
keyword. A function is generally a named unit of code which can be called from other
parts of a program. In Python a function may have one or more variables as arguments,
which receive their values from the calling program. In Example 1.6, the function f has
three arguments vo, a, t, which are listed in parentheses in the line defining f. All three
arguments must be provided when the function is called.
10 Mathematical Methods using Python: Applications in Physics and Engineering

Inside the indented code of the function definition, the evaluation of (1.3.1) is stored in
the variable y. The variable y is a local variable used by the function, and its value is not
known outside the definition of the function f . By contrast, the variable ypos is a global
variable, whose numerical value is known to the entire code.
The return y statement sends the variable y as the result of the calculation to the
calling code. One can specify more than one variable in the return statement by separating
them with commas.
Suppose we wanted to calculate the value of the function f for vo = 2, a = 1 and t = 3.
This can be done using the syntax f(2,1,3). For example, p = f(2,1,3) would store the
value 10.5 in the variable p.
However, Example 1.6 asks us to calculate the particle’s position at multiple times. One
can construct for loops in Python which execute blocks of code repeatedly. In Example 1.6
we create a for loop for such a purpose. However, before we begin the for loop, the code
line ypos = [] initializes an empty list and which will be used to store the position of the
particle at various times. Notice that this line of code is unindented because, as a global
variable, ypos is defined outside of the function f.
To define a for loop, we need two things, a variable for iteration and a range for that
iteration. In Example 1.6, the variable of iteration is t which takes on the values in the
sequence range(4). The indented block of code following the for loop will be repeated
several times. In the first iteration of the loop, the variable t has the value of 0, the first
element of the sequence range(4). The function f is evaluated using f(1,2,t) which, in
this iteration of the loop, is the same as f(1,2,0). The value of f(1,2,0) is then appended
to the end of the list ypos by using the ypos.append(f(1,2,t)) command.
In the second iteration of the loop, the variable t has the value of 1 and the process is
repeated. Afterwards, the loop has two more iterations, t = 2 and t = 3. The integer 3 is
the last element of range(4) and, therefore the loop stops after that iteration.

Example 1.6: A simple function in Python, and a FOR loop

Create a function f(vo,a,t) which evaluates the position y of a particle starting at the origin,
moving with initial speed v0 , under a constant acceleration a, and at time t:
1 2
y = v0 t + at (1.3.2)
2
Use a for loop so that the function f is called repeatedly to evaluate the position of the particle
at times t = 0, 1, 2 and 3 seconds.

Solution:
As outlined above, we construct the for loop using range(4). The function f is called repeatedly
inside the loop, to evaluate the position variable ypos. The value of f is added (appended) to
the list ypos by using the ypos.append(f(1,2,t)) command.

print('-'*28,'CODE OUTPUT','-'*29,'\n')

def f(vo,a,t): # define function f


y = vo*t+a*t**2/2 # functions require indentation
return y # return the variable y to the calling code

ypos = [] # create the empty list ypos


for t in range(4): # for loops require indentation
Introduction to Python 11

ypos.append(f(1,2,t)) # add the value of f to the list ypos

print('position y(t) = ',ypos)

---------------------------- CODE OUTPUT -----------------------------

position y(t) = [0.0, 2.0, 6.0, 12.0]

In some cases the functions we need in our code are simple and they depend only on one
variable, so that we can use a simple function structure called a lambda function. Example
1.7 defines a lambda named function f, which evaluates the position ypos of the particle
based on (1.3.1).

Example 1.7: A lambda function

Repeat the previous example by using a lambda function.

Solution:
Note that when using this simpler type of function, the variables v0 and a are treated as global
variables with fixed values v0 = 1 and a =2.

print('-'*28,'CODE OUTPUT','-'*29,'\n')

vo, a = 1, 2 # global variables vo, a


f = lambda t: vo*t+a*t**2/2 # define lambda function f(t)

ypos = [] # empty list ypos

for t in range(4): # for loops require indentation


ypos.append(f(t)) # add value of f to the list ypos

print('position y(t) = ',ypos)

---------------------------- CODE OUTPUT -----------------------------

position y(t) = [0.0, 2.0, 6.0, 12.0]

In many occasions we need to execute parts of the code only if certain conditions are
true. In Python such conditional statements are implemented using the if, elif and else
keywords, as in Example 1.8. The conditional statement also uses indentation, just like the
functions and for loops.
12 Mathematical Methods using Python: Applications in Physics and Engineering

Example 1.8: A conditional loop

Repeat the previous example, however this time use an if statement inside the for loop, so that
the code stores only values of the position which are smaller than 7.

Solution:
In this example the ypos variable is evaluated and stored only if the conditional statement f(t)<7
is true, otherwise the code line ypos.append(f(t)) is ignored.

print('-'*28,'CODE OUTPUT','-'*29,'\n')

vo, a = 1, 2 # global variables xo, vo, a


f = lambda t: vo*t+a*t**2/2 # define lambda function f(t)

ypos = [] # empty list ypos

for t in range(4): # for loops require indentation


if f(t)<7: # if statements require indentation
ypos.append(f(t)) # if f(t)<7 is true, then add value
# of f(t) to the list ypos
# if f(t)>=7, then ignore this statement

print('position y(t) = ',ypos)

---------------------------- CODE OUTPUT -----------------------------

position y(t) = [0.0, 2.0, 6.0]

Python allows function arguments to have default values. If a function is called without
a particular argument, its default value will be taken. By using this feature, the same
function can be called with different number of arguments. The arguments without default
values must appear first in the argument list and they cannot be omitted while invoking
the function. Example 1.9 shows how a function f can be called using three arguments in
the form f(vo, t, a = 2.0), or using two arguments in the form f(vo, t).

Example 1.9: Named variables in functions

In Example 1.6 we used the function f(vo,a,t). Write a code which sets the default value of a
to be 2. Using vo = 1, calculate f using the default value of a, and also using the value a= 3,
for the time values of t = 0, 1, 2 and 3.

Solution:
Note that for the default parameter value, f is called using only two parameters as f(vo, t),
with the third parameter a using the default value of a = 2. However, all three parameter values
must be specified in the case where the default value of a is no longer used.
Introduction to Python 13

def f(vo,t,a=2): # define function f with default a=2


y = vo*t+a*t**2/2
return y

ypos, ypos2 = [], [] # empty lists

for t in range(4): # for loop evaluates function f twice


ypos2.append(f(1,t)) # call f with 2 arguments and default a=2
ypos.append(f(1,t,3)) # call f with 3 arguments and a=3

print('-'*28,'CODE OUTPUT','-'*29,'\n')

print('Using three calling parameters, position y(t)=',ypos)


print('Using two calling parameters, position y(t)= ',ypos2)

---------------------------- CODE OUTPUT -----------------------------

Using three calling parameters, position y(t)= [0.0, 2.5, 8.0, 16.5]
Using two calling parameters, position y(t)= [0.0, 2.0, 6.0, 12.0]

1.4 IMPORTING PYTHON LIBRARIES AND PACKAGES


One of the major advantages of Python is the availability of modules, libraries and packages
for various scientific applications. In this text, we will use the term library as a generic term
for all three.
There are several different ways to import Python libraries and the most common meth-
ods are explained in Example 1.10, by using the numpy library and the cosine function cos()
as an example.
The simplest way to import functions from the NumPy library is using numpy.cos(0.5),
where the function is invoked using the form library_name.function_name() .
In the second method, we use an alias for the module name, so that we do not have to
type repeatedly long module names. In this example import numpy as np, and we call the
cosine function in the form np.cos(0.5).
In the third method of importing a function we use from numpy import cos and it is
understood that the cos() function in the code will refer to the numpy library.
In the fourth method we use the character * as a wild card for importing all available
functions with the code line from numpy import *. In this last method, we do not need
to type the name of the alias or library. However, one must be careful when using the *
method, since this can cause trouble when more than one modules are imported, which
could be using the same name for different functions.
Other common libraries we will work with are SymPy (Symbolic Python), SciPy (Sci-
entific Python) and the graphics library Matplotlib. These libraries are discussed later in
this chapter.

Example 1.10: Importing libraries

Write a Python code to demonstrate the four methods described above for importing the numpy
package, and then evaluate the cosine function cos(0.5) in each method.
14 Mathematical Methods using Python: Applications in Physics and Engineering

Solution:
The comments in this code explain the differences between the four methods of loading and using
the package.

print('-'*28,'CODE OUTPUT','-'*29,'\n')

import numpy # method 1: use name.function() syntax


print('Using NumPy function, result is: ', numpy.cos(0.5))

import numpy as np # method 2: use alias np, instead of numpy


print('Using np shorthand notation, result is: ', np.cos(0.5))

from numpy import cos # method 3: import only function cos() from numpy
print('Importing just the NumPy function, result is: ', cos(0.5))

from numpy import * # method 4: import all necessary from numpy


print('Importing all NumPy functions, result is: ', cos(0.5))

---------------------------- CODE OUTPUT -----------------------------

Using NumPy function, result is: 0.8775825618903728


Using np shorthand notation, result is: 0.8775825618903728
Importing just the NumPy function, result is: 0.8775825618903728
Importing all NumPy functions, result is: 0.8775825618903728

Libraries are sometimes organized into multiple modules. For example, the mod-
ule name A.B indicates a module B contained within a library named A. For exam-
ple, numpy.random.normal() refers to the function normal() contained within the mod-
ule random of the library numpy. The general format for this type of function is
package.module.function().

1.5 THE NUMPY LIBRARY


NumPy is the core Python library for numerical computing. NumPy supports operations
on compound data types like arrays and matrices. The first thing to learn is how to create
arrays and matrices using the NumPy library. Python lists can be converted into multi-
dimensional arrays.
In this book we usually adopt the standard convention and import NumPy using the
alias name np, with the code line import numpy as np. As mentioned above, one can also
import NumPy functions using the syntax from numpy import *. If NumPy is the only
package being used in the code, then there is no possibility of any function name conflicts.

1.5.1 CREATING NUMPY ARRAYS


The fundamental object provided by the NumPy library is the ndarray. We can think of
a 1D (1-dimensional) ndarray as a list, a 2D (2-dimensional) ndarray as a matrix, a 3D
(3-dimensional) ndarray as a 3-tensor and so on.
Introduction to Python 15

Using the function np.array() we can create a NumPy array from a Python sequence,
such as a list, a tuple or a list of lists. For example
a = np.array([1,5,2])
creates a 1D NumPy array from a Python list.
There are several other functions that can be used for creating different types of arrays
and matrices. Some examples of such array functions are shown in Table 1.2.

Table 1.2
NumPy functions for creating arrays and matrices.
Function Description
np.array(a) Create N-dimensional NumPy array from sequence a
np.arange(start, stop, step) Create an evenly spaced 1D array from start to stop,
excluding the stop value.
np.linspace(start, stop, N) Create a 1D array with length equal to N,
including the start and stop value.
np.zeros(shape) Create array of given shape and type, filled with zeros
np.ones(shape) Create an array of given shape and type, filled with ones
np.random.random(shape) Create an array of given shape and type,
filled with random float numbers from 0 to 1
np.reshape(array, newshape) Changes the dimensions of a 1D array

Example 1.11 applies some of these array functions to create various types of arrays. In
the first two lines of code, notice that when we print a NumPy array it looks a lot like a
Python list, except the elements are separated by spaces, while in a list the elements are
separated by commas.
The function np.arange(start,stop,step) is very similar to the list function
range(start,stop,step) that we saw before when discussing lists. In Example 1.11,
the code line np.arange(0,3.5,.5) creates a 1D NumPy array with values from 0 to 3.5
in steps of .5, excluding the end value of 3.5.
The function np.linspace(start,stop,N) is slightly different, since we specify the
number of points N between the start and end values, instead of the step in the array. In
the same example, np.linspace(0,8,6) creates an array with exactly 6 elements between
0 and 8, including the end value 8.
Similarly np.zeros(5) creates a 1D NumPy array of zeros of length 5. Similarly,
np.zeros(2,1) creates a 2D NumPy array of zeros with 2 rows and 1 column. The code
line np.random.random([1,2]) will generate a matrix with one row and two columns, with
random values between 0 and 1.
Example 1.11 demonstrates various types of arrays, and how to use the np.arange(),
np.linspace(), np.zeros() and np.random.random() functions.
16 Mathematical Methods using Python: Applications in Physics and Engineering

Example 1.11: Creating arrays in Python

Write a simple code to show how to create arrays using the np.arange(), np.linspace(),
np.zeros() and np.random.random() functions.

Solution:
The comments in the code explain the various commands.

import numpy as np
print('-'*28,'CODE OUTPUT','-'*29,'\n')
print('printing the list [1,2,3]: ',[1,2,3])
print('printing the array np.array([1,2,3]): ',np.array([1,2,3]),'\n')

print('np.arange(5) gives: ',np.arange(5))


print('np.arange(0,3.5,.5) gives: ',np.arange(0,3.2,.5),'\n')
# array from 0 to 3.5 steps 0.5 (excluding 7)

print('np.linspace(0,8,6) gives: ',np.linspace(0,8,6),'\n')


# create array with 6 values between 0 and 8

print('array with zeros: ',np.zeros(5)) # generate array with 5 zeros


print('array with ones: ',np.ones([2,1]),'\n')
# generate two rows and one column, with ones

print('array with random values: ',np.random.random([1,2]))


# generate random numbers in one row and two columns, in interval (0,1)

---------------------------- CODE OUTPUT -----------------------------

printing the list [1,2,3]: [1, 2, 3]


printing the array np.array([1,2,3]): [1 2 3]

np.arange(5) gives: [0 1 2 3 4]
np.arange(0,3.5,.5) gives: [0. 0.5 1. 1.5 2. 2.5 3. ]

np.linspace(0,8,6) gives: [0. 1.6 3.2 4.8 6.4 8. ]

array with zeros: [0. 0. 0. 0. 0.]


array with ones: [[1.]
[1.]]

array with random values: [[0.26177687 0.78577744]]

1.5.2 ARRAY FUNCTIONS, ATTRIBUTES AND METHODS


In this section we present a brief overview and examples of working with Python arrays. We
will look at how we can access the properties (or attributes) of an array and will examine
some of the functions that can be used with NumPy arrays.
Introduction to Python 17

Table 1.3
Useful commands (methods) for extracting the properties or attributes of an array.
Command Description
A.dtype prints the data type for NumPy array A
A.ndim prints the number of dimensions for NumPy array A
A.size prints the size (total number of elements) for NumPy array A
A.shape finds the number of rows and columns for NumPy array A

Example 1.12 applies various functions on arrays and also shows how we can extract some
of the important properties of arrays. Some examples of useful commands for extracting
the properties of arrays are shown in Table 1.3.
Note that the syntax in Table 1.3 is A.dtype, A.size etc. These are examples of using
methods objects in Python, as opposed to the functions objects we have looked at so far in
this book. Recall also that we use the function type(A) for a list A , but we use the similar
command A.dtype for a NumPy array A. This is an example of using a function versus
using a method.
Functions are called by placing argument expressions in parentheses after the function
name as in type(a), where a is an object (list, string, float, etc.). The functions that we
define in this book will always be called using the function name first, followed in parenthesis
by all of the arguments of the function.
Methods are somewhat similar to functions, but they are called using the dot notation,
such as A.dtype. Loosely speaking, methods are always attached to a specific object, while
functions are isolated. Another example of a function versus a method is the implementation
of the dot and cross products of two vectors A and B in SymPy and NumPy. In SymPy
the dot product is implemented as a method A.dot(B), while in NumPy the dot product
is represented as a function dot(A,B). We will later see several more different types of
functions and methods within the NumPy, SymPy and SciPy packages used in this book.
Example 1.12 shows how we can use some of these functions with arrays. All entries in
a NumPy array are of the same data type. We will mostly work with numeric arrays which
contain integers, floats, complex numbers or booleans. We will also mostly be working with
the default integer type numpy.int64 and the default float type numpy.float64. We can
access the datatype of a NumPy array A by its A.dtype attribute. In Example 1.12 we
create a 2D NumPy array from a list of lists of integers using the lines of code
A = np.array([[1,2,3],[4,5,6]])
A.dtype
prints out dtype(′ int32′ ) i.e the data is of integer type and is represented in the com-
puter’s memory by 32-bits. Similarly, A.ndim tells us that A has 2 dimensions, with the
first dimension corresponding to the vertical direction counting the rows, and the second
dimension corresponds to the horizontal direction counting the columns.
In Example 1.12, A.shape gives (3, 2), i.e. the result is a tuple (3,2) with 3 rows and
2 columns. Similarly, we create a 1D array using u = np.linspace(0,1,5), and u.dtype
prints out dtype(′ float64′ ) i.e. the data are floating type real numbers represented by 64
bits.
Finally, we can find out the total elements in array A with A.size.
18 Mathematical Methods using Python: Applications in Physics and Engineering

Example 1.12: Attributes of Nympy arrays

Write a simple code to demonstrate how to use A.dtype , A.ndim , A.shape and A.size with a
NumPy array A=[[1,2,3],[4,5,6]].

Solution:

print('-'*28,'CODE OUTPUT','-'*29,'\n')
import numpy as np

A = np.array([[1,2,3],[4,5,6]])
print('A = ',A)
print('Data type of A is: ', A.dtype,'\n')

u = np.linspace(0,1,5)
print('u = ',u)
print('Data type of u is: ', u.dtype,'\n')

A = np.array([[1,2,3],[3,4,5]])
print('A = ',A)
print('dimension of A is:', A.ndim)
print('shape of A is: ', A.shape)
print('size of A is: ', A.size)

---------------------------- CODE OUTPUT -----------------------------

A = [[1 2 3]
[4 5 6]]
Data type of A is: int32

u = [0. 0.25 0.5 0.75 1. ]


Data type of u is: float64

A = [[1 2 3]
[3 4 5]]
dimension of A is: 2
shape of A is: (2, 3)
size of A is: 6

In the next section we see how to carry out arithmetic operations with various types of
arrays.

1.5.3 ARITHMETIC OPERATIONS WITH NUMPY ARRAYS


Mathematical functions in NumPy are vectorized, and a partial list of functions we can use
to compute with NumPy arrays is given in Table 1.4.
Vectorized functions operate element-wise on arrays and produce new arrays as output.
For example
np.sin(2*np.pi*x)
Introduction to Python 19

computes the values for each elements of the array


x = np.arange(0,1.25,0.25)
These vectorized functions compute values across arrays very quickly. NumPy also provides
mathematical constants such as π (np.pi), and e (np.e).
We can modify the contents of a NumPy array using indexing and slicing, just as in the
case of lists.

Table 1.4
Partial list of useful array functions in Python.
Array functions in NumPy
np.sum np.argmax np.min np.std
np.max np.argmin np.mean np.prod
Mathematical functions in NumPy
np.sin np.exp np.arcsin
np.cos np.log np.arccos
np.tan np.log10 p.arctan
Mathematical constants in NumPy
np.pi np.e

Arithmetic operations are applied to NumPy arrays element-by-element: these include


addition +, subtraction -, multiplication *, division / and exponentiation **. See Example
1.13 for a demonstration of the addition of two NumPy arrays.
Normally we can only add vectors or matrices of the same size. However, NumPy has
a set of rules called broadcasting, which allows the combination of arrays of different sizes
when the process makes sense. For example, we can add a constant to a 1D NumPy array,
by using the expression
1+np.array([5,6,7])**2
In this example of broadcasting, the array np.array([5,6,7]) is squared, and then we
add the array of ones [1. 1. 1.] which has the same shape. Here we are adding the scalar
number 1 to a 1D NumPy array of length 3, and the broadcasting rule allows us to use a
very simple syntax.
Example 1.13 demonstrates various array operations. For example, to compute the
average or mean of the values in an array, we use
np.mean([5,6,7])
Similarly, to find the index of the maximum element in the array, we use
np.argmax([5,6,7])
which gives the value of the index 2, i.e. it identifies the third element in the array as the
max value.
Array functions apply to multi-dimensional arrays as well, but we have to choose along
which axis of the array to apply the function. For example, for the array
M = np.array([[2,4,2],[2,1,1],[3,2,0]])),
20 Mathematical Methods using Python: Applications in Physics and Engineering

the function
np.sum(M,axis=0)
will sum the columns of M. However, the function
np.sum(M,axis=1)
will sum the rows of M. In a similar manner, a 3D array of size 3 x 3 x 3 can be summed
over each of its three axes.

Example 1.13: Arithmetic operations on arrays- Broadcasting

Define two NumPy arrays, a and b from the lists [1, 2, 3] and [4, 5, 6], respectively. In addition,
define a 3 × 3 matrix M of your choosing as a NumPy array.
Write a simple code to demonstrate the following:

1. The use of the functions mean(a), argmax(a) , std(a) for the NumPy array a.

2. The result of a + b and a * b

3. Broadcasting, using 1 + a**2

4. The use of the functions np.sum(M,axis=0) , np.sum(M,axis=1) .

Solution:

import numpy as np
print('-'*28,'CODE OUTPUT','-'*29,'\n')

a = np.array([1,2,3])
b = np.array([4,5,6])
M = np.array([[2,4,2],[2,1,1],[3,2,0]])

#Part 1
print('mean of elements in array a = ',np.mean(a))
print('std dev of elements in array a = ',np.std(a))
print('max of elements in array a = ',np.max(a))
print('sum of elements in array a = ',np.sum(a),'\n')

#Part 2
print('a + b = ' , a+b)
print('a * b = ', a*b, '\n')

#Part 3
print('1 + a**2 = ', 1 + a**2,'\n')

#Part 4
print('matrix M =',M,'\n')
print('sum of elements of M along axis=0 (rows) = ',np.sum(M,axis=0))
print('sum of elements of M along axis=1 (columns) = ',np.sum(M,axis=1))

---------------------------- CODE OUTPUT -----------------------------

mean of elements in array a = 2.0


std dev of elements in array a = 0.816496580927726
Introduction to Python 21

max of elements in array a = 3


sum of elements in array a = 6

a + b = [5 7 9]
a * b = [ 4 10 18]

1 + a**2 = [ 2 5 10]

matrix M = [[2 4 2]
[2 1 1]
[3 2 0]]

sum of elements of M along axis=0 (rows) = [7 7 3]


sum of elements of M along axis=1 (columns) = [8 4 5]

1.5.4 INDEXING AND SLICING OF NUMPY ARRAYS


NumPy arrays can be indexed, sliced and copied, just like Python Lists.
Example 1.14 shows how to use slicing and indexing in multidimensional NumPy array.
For example, the fourth element in array v is accessed with v[3] and we can use two indexes
v[1,2] to find the element at row index 1 and column index 2. Similarly v[-1,-1] accesses
the last element. The syntax v[2,:] addresses the row with index 2, and v[:,3] addresses
the column with index 3.
We can also build bigger arrays by stacking smaller arrays along different dimensions,
using the horizontal and vertical stacking functions np.hstack and np.hstack.

Example 1.14: Indexing and slicing of NymPy arrays

(a) Define a 3 × 3 matrix v of your choosing and demonstrate the use of indexing with v[3],
v[1,2] and v[-1,-1].
(b) What elements of the matrix correspond to v[2,:] and v[:,3] ?
(c) Define two 1 × 3 matrices, and demonstrate the use of the horizontal and vertical stacking
functions np.hstack() and np.hstack().

Solution:
In the Python code, the pprint package is imported and used to format the code output for the
printed matrix.

import numpy as np
print('-'*28,'CODE OUTPUT','-'*29,'\n')

import pprint
pp = pprint.PrettyPrinter(width=41, compact=True)

# define 3x3 matrix using NumPy array


v = np.array([[1,2,3],[4,5,6],[7,8,9]])

print('array v = ')
pp.pprint(v)
22 Mathematical Methods using Python: Applications in Physics and Engineering

print('The third element v[2] = ',v[2],'\n')

print('The element at row index 1 and column index 2=',v[1][2])


print('The element v[1,0] = ',v[1,0])
print('The last element v[-1,-1] = ',v[-1,-1],'\n')

print('The column with index 0 = ',v[:,0])


print('The row with index 2 = ',v[2,:],'\n')

x = np.array([1,1,1])
y = np.array([2,2,2])
print('array x = ',x)
print('array y = ',y)
print('vertical stack of x,y,x = ',np.vstack((x,y,x)))
print('horizontal stack of x,y,x = ',np.hstack((x,y,x)))

---------------------------- CODE OUTPUT -----------------------------

array v =
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
The third element v[2] = [7 8 9]

The element at row index 1 and column index 2= 6


The element v[1,0] = 4
The last element v[-1,-1] = 9

The column with index 0 = [1 4 7]


The row with index 2 = [7 8 9]

array x = [1 1 1]
array y = [2 2 2]
vertical stack of x,y,x = [[1 1 1]
[2 2 2]
[1 1 1]]
horizontal stack of x,y,x = [1 1 1 2 2 2 1 1 1]

1.6 THE MATPLOTLIB MODULE


Matplotlib is a Python library that can generate many different types of plots and graphical
representations of data, using just a few lines of code. The user has full control of line
styles, font properties, axes properties, etc. Often data points for the plotting functions are
supplied as Python lists or as NumPy arrays.
In the next two subsections we will see how to create two and three-dimensional plots
using Matplotlib. We will also briefly discuss two different methods of using Matplotlib,
namely object oriented programming versus procedural programming.
Introduction to Python 23

1.6.1 2D PLOTS USING MATPLOTLIB


The general procedure to create a 2D plot is to first import the Python library Matplotlib
and its submodule pyplot. Typically we will import the matplotlib.pyplot submodule
using the short-hand alias plt. Next we create two sequences of x-values and y-values, and
then use the general plot command
plt.plot(x,y,[fmt],**kwargs)
Here [fmt] is an optional string format and **kwargs are optional keyword arguments
specifying the properties of the plot. To improve the appearance of the plot, we use
pyplot() functions to add a figure title, legend, grid lines, etc. Finally, the line plt.show()
displays the figure.
Let’s begin with a basic example, solving a simple physics problem that you are already
familiar with. A physicist throws a ball straight up with an initial speed v0 = 5 m/s. We
want to plot the position y(t) as a function of time, and also find numerically the maxi-
mum height reached by the ball. You recall from Introductory Physics that the kinematic
equations for this problem are:
1
y = v0 t − g t2 (1.6.1)
2
v(t) = v0 − g t (1.6.2)
where g =9.8 m/s2 is the acceleration of gravity. Example 1.15 shows how we would solve
this problem using the numerical capabilities of Python.

Example 1.15: Example of plot and numerical evaluation

Write a code to evaluate and plot the kinematic equation (1.6.1), from t = 0 to t =1 s with
vo = 5 m/s.

Solution:
The first line in the code import numpy as np causes Python to import the NumPy library, with
the alias np. We import the Python library Matplotlib and its submodule pyplot, in order to plot
the position y(t). The code imports the matplotlib.pyplot submodule using the short-hand
alias plt. After the libraries are imported, we define the initial condition variable vo and the
acceleration of gravity g, in a single line vo, g = 5, 9.8.
We need to tell Python for which values of time t we will be computing the position y(t). In this
case, we use t=np.linspace(0,1,100) to define the array with the values of times t, which will
be used to compute y(t). We next use a list comprehension in the form
y=[vo*u-g*u**2/2 for u in t]
to obtain the array y containing the values of y(t).
The pyplot commands plot, title, ylabel, xlabel are used to improve the appearance of
the plot in Figure 1.1, and finally plt.show() prints the plot. The last 4 lines in the code show
how to evaluate numerically the maximum height ymax and the corresponding time tmax, by
applying the functions max() and argmax() respectively.

print('-'*28,'CODE OUTPUT','-'*29,'\n')
import numpy as np
import matplotlib.pyplot as plt
vo, g = 5, 9.8 # define values of vo, g
24 Mathematical Methods using Python: Applications in Physics and Engineering

t = np.linspace(0,1.03,100) # create sequence of times


y = [vo*u-g*u**2/2 for u in t] # create sequence of positions, then plot y(t)

plt.plot(t,y)

plt.title('Ball thrown straight up') # add title to plot


plt.ylabel('Vertical distance y(t)') # add labels for x and y axes
plt.xlabel('Time t [s]')

ymax = max(y) # find position ymax


tmax = t[np.argmax(y)] # find time tmax

print('Max height reached = ',f'{ymax:.4f}', ' m')


print('Time to reach ymax = ',f'{tmax:.4f}',' s')

plt.show()

---------------------------- CODE OUTPUT -----------------------------

Max height reached = 1.2755 m


Time to reach ymax = 0.5098 s

Ball thrown straight up

1.2

1.0
Vertical distance y(t)

0.8

0.6

0.4

0.2

0.0

0.0 0.2 0.4 0.6 0.8 1.0


Time t [s]

Figure 1.1 Plot of the kinematic equation (1.6.1), from t = 0 to t =1 s with vo = 5 m/s.

We can improve further the plots by specifying various options inside the plt.plot()
function. For example, we specify the color e.g. by name as in color=′ red′ , or by a RGB tu-
ple such as (1,0,1). We can also specify the type of line to be used with linestyle=′ dashed′ ,
the type of marker for data points with marker=′ o′ , the linewidth with linewidth=2 etc.
Introduction to Python 25

It is very convenient to use combined format strings as in the command


plt.plot(x,y,′ rd--′ ) where the string ′ rd--′ ) signifies a red line ( ’r’), a diamond
marker (’d’) and a dashed line (--).
Examples of colors are b blue, g green, r red, c cyan, m magenta, y yellow, k black, w
white. Examples of character Markers are. point, o circle, v triangle down, ˆ triangle up,
s square, p pentagon, * star, + plus, x x, D diamond. Finally, examples of linestyles are -
solid line style, -- dashed line, -. dash-dot line, : dotted line.
The graphical commands in this example are an example of procedural programming.
Next, we will use the Matplotlib module to produce 3D plots using object oriented pro-
gramming.

1.6.2 3D PLOTS USING MATPLOTLIB


Example 1.16 demonstrates how to plot a surface z = f (x, y) in 3D.

Example 1.16: Graphics: Plotting a surface z = f (x, y)

Write a Python code to plot the surface function z = f (x, y) = x+y +3 in 3D, when −3 ≤ x ≤ 3
and −3 ≤ y ≤ 3.

Solution:
The 3D plot in the example is created using the plot_surface() function within the matplotlib
library. The lines fig = plt.figure() and and fig.add_subplot(projection =′ 3d′ ) create
the 3D plot, and the wireframe style is used for the plot.
The NumPy command meshgrid(x, x) creates double arrays X,Y from the single NumPy ar-
ray x. It is necessary to created double arrays which are required as inputs for the function
plot_surface(X,Y,Z).
The plotting function plot_wireframe(X,Y,Z) plots the 3D surface of the plane z = f (x, y) =
3 + x + y with the result shown in Figure 1.2.

import numpy as np
import matplotlib.pyplot as plt

# surface plot for z=3+x+y


x = np.arange(-3, 3, 0.6) # grid of points on x-axis
X, Y = np.meshgrid(x, x) # grid of points on xy-plane
Z= 3+X+Y # values of z for points on the xy-grid

# plot 3D surface using object oriented programming commands


# define the objects fig and axes for 3D plotting
fig = plt.figure()
axes = fig.add_subplot(projection ='3d')

# plot 3D surface using wireframe style


axes.plot_wireframe(X, Y, Z, color='skyblue')

axes.set_xlabel('X') # labels for x,y,z axes


axes.set_ylabel('Y')
axes.set_zlabel('Z')
26 Mathematical Methods using Python: Applications in Physics and Engineering

axes.text(-2.6,2,6,'z=f(x,y)=3+x+y') # add text to the plot

plt.show()

Figure 1.2 Plot of a 3D surface z = f (x, y) from Example 1.16, using MatPlotLib.

1.7 SYMBOLIC COMPUTATION WITH SYMPY


Symbolic Computation involves using a computer to help find closed-form solutions to differ-
ential equations, integrals, eigenvalues, and many more types of symbolic evaluations. For
example, we can enter the equation or integral we want solved, and the computer program
returns a closed form solution, if it exists.
Python cannot perform symbolic manipulations by itself, so we need to import the
SymPy library in order to expand Python’s capabilities. This is sometimes done in the first
line of the code with import sympy as sym, which causes Python to import the SymPy
library with the alias sym. Most often, we will import from SymPy only the functions we
need.
As an example of a symbolic type of computation, we will use SymPy to solve again
symbolically the simple physics problem of throwing a ball straight up with an initial speed
v0 = 5 m/s. We want to evaluate symbolically the maximum height ymax reached by the
ball (neglecting air resistance), and how long it takes to reach this maximum height.
Introduction to Python 27

As mentioned previously in this chapter, the kinematic equations for this problem are:
1
y = v0 t − g t2 (1.7.1)
2
v(t) = v0 − g t (1.7.2)
By setting the speed v(t) = v0 − g t = 0 at the maximum height reached by the ball, we
find the corresponding time t = v0 /g. Substituting this value of t into (1.7.1) we find the
maximum height:
   2
v0 1 v0 v2
ymax = v0 − g = 0 (1.7.3)
g 2 g 2g
Example 1.17 shows how we would solve this problem using the symbolic capabilities of
Python.

Example 1.17: Example of symbolic evaluation

Use SymPy to solve again the problem of throwing a ball straight up with an initial speed
v0 = 5 m/s. Evaluate symbolically the maximum height ymax reached by the ball (neglecting air
resistance), and how long it takes to reach this maximum height.

Solution:
The following Python code evaluates the time tmax and the maximum height ymax , starting from
(1.7.1) and (1.7.2). In this example, the SymPy library includes the function solve and the
method .subs which can help us solve algebraic equations.
Notice that we tell Python that the variables vo, t, g need to be defined, using the symbols
command, and that we also include the option real=True to signify that they are to be treated
as real variables.
The code line solve(vo-g*t,t) solves symbolically the equation v0 − g t = 0 for the variable t,
while the line y.subs(t,tmax) substitutes symbolically the value of t with tmax.

from sympy import symbols, solve


print('-'*28,'CODE OUTPUT','-'*29,'\n')

vo, t, g = symbols('vo, t, g ',real=True) # define variables

# solve equation for tmax symbolically using solve() function


tmax = solve(vo-g*t,t)[0]
print('Time to reach max height=',tmax)

y = vo*t-g*t**2/2
# substitute tmax in y(t) to find ymax, using method .subs
print('Max height reached = ',y.subs(t,tmax))

---------------------------- CODE OUTPUT -----------------------------

Time to reach max height= vo/g


Max height reached = vo**2/(2*g)

In the next section we provide an example which shows how to use the lambdify function
in Python.
28 Mathematical Methods using Python: Applications in Physics and Engineering

1.8 THE LAMBDIFY() FUNCTION IN PYTHON


Example 1.18 shows how one can combine the results from NumPy and SymPy libraries, by
using the lambdify() function. The lambdify() function can calculate numerical values
from SymPy expressions.
In Example 1.18, we are asked to evaluate a symbolic derivative and then plot its result.
We use SymPy to evaluate the symbolic derivative of a function. However, lambdify must
then be used, so that we can numerically evaluate the result before we create the plot.

Example 1.18: Example of using the lambdify function

Use SymPy to evaluate the symbolic derivative of the function f = a sin(b t) with respect to time
t, and plot the function f (t) and its derivative in the interval t = 0 to t = 6. Use the numerical
values a = 1 and b = 2.

Solution:
The Python code imports the lambdify function with the code line
from sympy.utilities.lambdify import lambdify
Notice that we tell Python that the variables a, b, t need to be defined using the symbols
command, and that we also include the option real=True to signify that they are to be treated
as real variables. The diff(f,t) command is used to evaluate the symbolic derivative of the
function f = a sin(b t) and the result is stored in the variable deriv.
Next, f.subs(a:1,b:2) substitutes the numerical values a = 1 and b = 2 into the symbolic
derivative, and code line
y = lambdify(t,f.subs(a:1,b:2))
creates a function y = f (t) which can be plotted using Matplotlib.
plt.subplot(1,2,1) creates the first of two subplots, arranged in 1 row and 2 columns, and the
last index 1 refers to the first subplot. Similarly, plt.subplot(1,2,2) creates the second of the
two subplots in Figure 1.3.

import matplotlib.pyplot as plt


import numpy as np
from sympy import symbols, sin, diff
from sympy.utilities.lambdify import lambdify

print('-'*28,'CODE OUTPUT','-'*29,'\n')

a, b, t = symbols('a,b,t',real=True) # define symbols

f = a*sin(b*t)
deriv = diff( f,t) # evaluate symbolic derivarive of f
print('Symbolic Derivative v=dy/dt: ',deriv)

tims = np.linspace(0,6,50) # sequence of times tims

# substitute a=1 and b=2 in f, using the .subs method


y = lambdify(t,f.subs({a:1,b:2}))

# plot y(t) and v(t)


plt.subplot(1,2,1) # first subplot, positions y(t)
Introduction to Python 29

plt.plot(tims,y(tims))
plt.xlabel('Time [s]')
plt.ylabel('y(t)')

u = deriv.subs({a:1,b:2}) # substitute a=1 and b=2 in deriv


v = lambdify(t,u) # lambdify creates derivative function v(t)

plt.subplot(1,2,2) # second subplot, speed v(t)


plt.plot(tims,v(tims))
plt.xlabel('Time [s]')
plt.ylabel('Speed v(t)=dy/dt')
plt.tight_layout() # create the 2 subplots with thight layout
plt.show()

---------------------------- CODE OUTPUT -----------------------------

Symbolic Derivative v=dy/dt: a*b*cos(b*t)

1.00 2.0

0.75 1.5

0.50 1.0
Speed v(t)=dy/dt

0.25 0.5
y(t)

0.00 0.0

0.25 0.5

0.50 1.0

0.75 1.5

1.00 2.0
0 2 4 6 0 2 4 6
Time [s] Time [s]

Figure 1.3 Graphical output of Example 1.18, showing subplots of a function f = a sin(b t) and
its derivative.

1.9 END OF CHAPTER PROBLEMS


1. A uniform distribution of random numbers – Create 100 random numbers x
from a uniform distribution using the random() function in Numpy. Plot these 100
random numbers on the xy-plane, and also in the form of a histogram. Find the
average and the standard deviation of these 100 numbers.
30 Mathematical Methods using Python: Applications in Physics and Engineering

2. A Gaussian distribution of random numbers – Create 100 random numbers


from a Gaussian distribution using the random.normal() function in Numpy, and
plot them as a histogram. Find their average and standard deviation.

3. Example of using functions in Python – Define the function f (x, m, k) =


e−m x cos(2π k x) and compute f (x) for three different combinations of values of m
and k.
(a) Plot the 3 functions on the same plot, using different colors and line types for each
curve.
(b) Annotate the graph with the values of m, k for each plot.

4. Using a grid of subplots – Plot three functions from the previous problem with
different values of k, m . Create a grid of three subplots. Label the axes and provide
a title for each graph, and choose different colors and line types for each curve. Save
the resulting graph to a .jpg or .png file.

5. Using lambda functions – Plot f (x) = x2 /10 and g(x) = sin x using lambda
functions, for the range x = 0 to x = 6. Create a grid of three subplots, one subplot
for each function and a third subplot showing both functions. Each function should
have its own color and line type.

6. Conditional statement – Write a code in which you solve a cubic equation x3 +


x2 +1 = 0, then the code determines and prints whether the roots are real or complex.
Use the solve() function in SymPy.
7. Defining and plotting piecewise functions – Using the conditional if statement,
define the piecewise function

1 x<5
f (x) = 2
x x≥5

and evaluate f (x) for x = 3 and x = 7, and plot f (x) from x =0 to x =10. Use the
piecewise() function in NumPy to evaluate this piecewise defined function.

8. The Fibonacci series – The Fibonacci series of numbers xn is defined by the re-
cursive sequence xn = xn−1 + xn−2 . Compute the first 17 values of the Fibonacci
sequence. You may want to use for loops, and you may also want to save your results
into an array using the append() function in order to add values to an array.
9. Solving algebraic equations – (a) Use symbolic computation to solve each of these
equations:

7x + 5 = 0
x2 − 5x + 2 = 0
x3 + 7x − 5 = 3
Note that you will get complex roots for some of the solutions.
(b) Use symbolic computation to solve the system of equations:

2x − 5y = 7
x+y =2
Introduction to Python 31

10. Polar plots – Graph the functions r = |cos θ| and r = |cos θ sin θ| using polar plots
in Python, for the range of angles θ =0 to θ = 2π.

11. Parametric plots in 3D – Write a Python code to plot the parametric line (x, y, z) =
(t, 1 + 2 cos t, −1 + 3 sin t) for the range of values t =0 to t = 9.
12. Calculating
  the powers of a matrix – Create the 2 × 2 square matrix A =
1 2
using a NumPy array, and use a for loop to calculate the matrix rep-
1 0
resenting the powers A2 , A3 and A4 etc. Two matrices A, B can be multiplied using
the matrix multiplication symbol @, in the form A@B.

13. Evaluation of product series for cos x – Define a Python function f (x, N ) con-
taining the parameters x and N , and evaluate the following product series for cos x:
N  
 4x2
cos x = 1−
π (2k − 1)2 )
2
k=1

Run the code for N = 10, 50, 100 terms and for a value of x = 1, and compare the
value of the above product with the value of cos x at x =1.

14. Evaluation of the sum of infinite series – Use the Sum() function and .doit()
in SymPy to evaluate the infinite sums:

(−1)n 2n+1 1 (−1)n 2n


∞ ∞
 ∞ ∞
 ∞

xk xk
x x2n x
n=0
(2n + 1)! n=0
(2n)! n=0
(2n)! k! k
k=0 k=0

15. Evaluation of infinite series for π 2 – Define a Python function f (x, N ) containing
the parameters x and N , and evaluate the following series: ‘

π2 (−1)n+1
N

=
12 n=1 n2

Run the code for N = 10, 50, 100 and compare the sum with the value of π 2 /12.

16. Constructing multidimensional arrays and lists –


(a) Use a list comprehension method to construct a list with the values of (x, x2 , x3 )
from x = 1 to 10.
(b) Use the functions zip() and the function list() in Python to create a list of
pairs (y1 , y2 ) from two arrays y1 and y2 .

17. The Bessel functions – The Bessel function Jp (x) of order p is defined by the
infinite series:

 (−1)n  x 2n+p
Jp (x) = (1.9.1)
n=0
Γ (n + 1) Γ (n + 1 + p) 2

where p > 0 and Γ(n) is the Gamma function. Write a Python function to evaluate
numerically this infinite series using the summation() function in SymPy. Evaluate
and plot the Bessel functions Jp (x) for p =0, 2 and for the range of values x = −20
to x =+20.
32 Mathematical Methods using Python: Applications in Physics and Engineering

18. Plots of the sum of terms in a Fourier series – Plot the first N = 5, 10, 20, 30
terms of the Fourier series for a sawtooth wave:

50  (1)n−1
∞ n π 
T (x) = sin x (1.9.2)
π n=0 n L

which is defined as f (x) = 5x for 0 < x ≤ 5, and as f (x) = −5x for 10≥ x > 5. The
length L = 5.
19. Plots of the sum of terms in a Taylor series – Plot the first N =5, 6, 8, 10 terms
of the Taylor series for cos x from x = 0 to x = 8.
(−1)n 2n
∞
T (x) = x (1.9.3)
n=1
2n + 1

20. 3D plots of random points – Write a Python code to plot 100 random points
(x, y, z) in 3D.
21. The Pauli matrices – Look up the 3 Pauli matrices σx , σy , σz , which are used
in Quantum Mechanics to described the spin of an electron. Verify the following
identities using matrix algebra in Python:
 
2 2 2 1 0
σx = σy = σz = −iσx σy σz = =I
0 1
σx σy = iσz σx σy + σy σx = 0 σx σy − σy σx = 2iσz
where I is the identity matrix.
22. Plotting circles, ellipses, rectangles, arrows – Look up the matplotlib.patches
library in Python, and write a code that plots a circle, an ellipse and several arrows
inside a rectangle on the xy-plane.
23. Symbolic matrix multiplication – The following matrix B represents a counter-
clockwise rotation of a point in the xy-plane by the angle ϕ about the z-axis.
 
cos ϕ − sin ϕ
B=
sin ϕ cos ϕ
Rotating a point by an angle ϕ1 and then by an angle ϕ2 , is carried out by multiplying
the corresponding matrices for the two angles. Use SymPy to show that the double
rotation is the same as performing a single rotation by the angle ϕ1 + ϕ2 .
24. Transpose and inverse of a matrix – Define a 3×3 matrix M with random integers
between 0 and 2 as elements. Write the Python code which finds the transpose of M ,
and verify that the product of M and its transpose is a symmetric matrix.
25. Complex numbers in electronics – Complex numbers are used in the description
of AC electrical circuits. Specifically, we use the complex impedance Z to describe
the properties of resistors, inductors and capacitors. The impedance of a resistor
R is a real number given by ZR = R, while an inductors L has a purely imaginary
inductive impedance ZL = i ω L, and capacitors C have a purely imaginary capacitative
impedance ZC = −i/(ω C).
(a) Calculate symbolically the real and imaginary parts of the total impedance Z =
Zc + ZR + ZL by using the functions Z.real and Z.imag commands.
(b) Obtain the value of Z by using the .subs function and the numerical values of
R = 5 Ohm, L = 1 mH, C = 1 mF and ω =10 s−1 .
Introduction to Python 33

26. Finding maxima, minima and inflection points – Given the function

f (x) = x−6 − x−12

with x > 0, evaluate its first and second derivatives using the diff() command in
SymPy. Also evaluate the max/min points and the inflection points (if any) for f (x).

27. Plotting the Bose Einstein distribution at different temperatures – The Bose
Einstein distribution was introduced for photons by Bose, and generalized to atoms
by Einstein. The expected number of particles n(E) in an energy state E and with
temperature T (in K) is:
1
n(E, T ) = E/(k T )
e B −1
where kB is the Boltzmann constant. Write a Python function that evaluates n(E, T ),
and plot this function for three different temperatures T =2000, 4000, 6000 K on the
same plot.
Use a range of E values from E =0 eV to E =30 eV and label the 3 plots appropriately,
and also use a different symbol for each plot.
28. 3D graphics – Create three-dimensional plots of these objects. In each case label
the axes and the plots.
(a) A 3D line defined by (x, y, z) = (t, 1 + 2t, 1 + 3 sin t)
(b) A cone of radius R = 1 and height H =1
(c) A sphere of radius R =1
(d) A cylinder of radius R = 1 and height H =1
(e) An ellipsoid with semi-major axes a = 1, b = 0.6 and c = 1
Random documents with unrelated
content Scribd suggests to you:
EULALIE—A SONG
I dwelt alone
In a world of moan,
And my soul was a stagnant tide,
Till the fair and gentle Eulalie became my
blushing bride—
Till the yellow-haired young Eulalie became
my smiling bride.

Ah, less—less bright


The stars of the night
Than the eyes of the radiant girl!
And never a flake
That the vapour can make
With the moon-tints of purple and pearl,
Can vie with the modest Eulalie's most
unregarded curl—
Can compare with the bright-eyed Eulalie’s
most humble and careless curl.

Now doubt—now Pain


Come never again,
For her soul gives me sigh for sigh,
And all day long
Shines, bright and strong,
Astarté within the sky,
While ever to her dear Eulalie upturns her
matron eye—
While ever to her young Eulalie upturns her
violet eye.
Annabel Lee
ANNABEL LEE
It was many and many a year ago,
In a kingdom by the sea,
That a maiden there lived whom you may
know
By the name of Annabel Lee;
And this maiden she lived with no other
thought
Than to love and be loved by me.

I was a child and she was a child,


In this kingdom by the sea;
But we loved with a love which was more
than love—
I and my Annabel Lee;
With a love that the wingèd seraphs of
heaven
Coveted her and me.

And this was the reason that, long ago,


In this kingdom by the sea,
A wind blew out of a cloud, chilling
My beautiful Annabel Lee;
So that her highborn kinsmen came
And bore her away from me,
To shut her up in a sepulchre
In this kingdom by the sea.

The angels, not half so happy in heaven,


Went envying her and me—
Yes!—that was the reason (as all men know,
In this kingdom by the sea)
That the wind came out of the cloud by
night,
Chilling and killing my Annabel Lee.

But our love it was stronger by far than the


love
Of those who were older than we—
Of many far wiser than we—
And neither the angels in heaven above,
Nor the demons down under the sea,
Can ever dissever my soul from the soul
Of the beautiful Annabel Lee.

For the moon never beams without bringing


me dreams
Of the beautiful Annabel Lee;
And the stars never rise but I feel the bright
eyes
Of the beautiful Annabel Lee;
And so, all the night-tide, I lie down by the
side
Of my darling—my darling—my life and my
bride,
In her sepulchre there by the sea,
In her tomb by the sounding sea.
SONNET—SILENCE
There are some qualities—some incorporate
things,
That have a double life, which thus is
made
A type of that twin entity which springs
From matter and light, evinced in solid
and shade.
There is a two-fold Silence—sea and shore—
Body and soul. One dwells in lonely
places,
Newly with grass o'ergrown; some
solemn graces,
Some human memories and tearful lore,
Render him terrorless: his name's "No
More."
He is the corporate Silence: dread him not!
No power hath he of evil in himself;
But should some urgent fate (untimely lot!)
Bring thee to meet his shadow (nameless
elf,
That haunteth the lone regions where hath
trod
No foot of man), commend thyself to God!
Silence
THE RAVEN
Once upon a midnight dreary, while I
pondered, weak and weary,
Over many a quaint and curious volume of
forgotten lore,
While I nodded, nearly napping, suddenly
there came a tapping,
As of some one gently rapping, rapping at
my chamber door.
"'Tis some visitor," I muttered, "tapping at
my chamber door—
Only this, and nothing more."

Ah, distinctly I remember it was in the bleak


December,
And each separate dying ember wrought its
ghost upon the floor.
Eagerly I wished the morrow;—vainly I had
sought to borrow
From my books surcease of sorrow—sorrow
for the lost Lenore—
For the rare and radiant maiden whom the
angels name Lenore—
Nameless here for evermore.

And the silken sad uncertain rustling of each


purple curtain
Thrilled me—filled me with fantastic terrors
never felt before;
So that now, to still the beating of my heart,
I stood repeating,
"'Tis some visitor entreating entrance at my
chamber door—
Some late visitor entreating entrance at my
chamber door;—
This it is, and nothing more."

Presently my soul grew stronger; hesitating


then no longer,
"Sir," said I, "or Madam, truly your
forgiveness I implore;
But the fact is I was napping, and so gently
you came rapping,
And so faintly you came tapping, tapping at
my chamber door,
That I scarce was sure I heard you,"—here I
opened wide the door;—
Darkness there, and nothing
more.

Deep into that darkness peering, long I


stood there wondering, fearing,
Doubting, dreaming dreams no mortals ever
dared to dream before;
But the silence was unbroken, and the
stillness gave no token,
And the only word there spoken was the
whispered word, "Lenore!"
This I whispered, and an echo murmured
back the word, "Lenore!"—
Merely this, and nothing more.

Back into the chamber turning, all my soul


within me burning,
Soon again I heard a tapping somewhat
louder than before.
"Surely," said I, "surely that is something at
my window lattice:
Let me see, then, what thereat is, and this
mystery explore—
Let my heart be still a moment and this
mystery explore;—
'Tis the wind and nothing
more."

Open here I flung the shutter, when, with


many a flirt and flutter,
In there stepped a stately raven of the
saintly days of yore;
Not the least obeisance made he; not a
minute stopped or stayed he;
But, with mien of lord or lady, perched
above my chamber door—
Perched upon a bust of Pallas just above my
chamber door—
Perched, and sat, and nothing
more.

Then this ebony bird beguiling my sad fancy


into smiling,
By the grave and stern decorum of the
countenance it wore,
"Though thy crest be shorn and shaven,
thou," I said, "art sure no craven,
Ghastly grim and ancient raven wandering
from the Nightly shore—
Tell me what thy lordly name is on the
Night's Plutonian shore!"
Quoth the Raven,
"Nevermore."

Much I marvelled this ungainly fowl to hear


discourse so plainly,
Though its answer little meaning—little
relevancy bore;
For we cannot help agreeing that no living
human being
Ever yet was blest with seeing bird above his
chamber door—
Bird or beast upon the sculptured bust
above his chamber door,
With such name as
"Nevermore."

But the raven, sitting lonely on the placid


bust, spoke only
That one word, as if his soul in that one
word he did outpour.
Nothing further then he uttered—not a
feather then he fluttered—
Till I scarcely more than muttered, "other
friends have flown before—
On the morrow he will leave me, as my
hopes have flown before."
Then the bird said,
"Nevermore."

Startled at the stillness broken by reply so


aptly spoken,
"Doubtless," said I, "what it utters is its only
stock and store,
Caught from some unhappy master whom
unmerciful Disaster
Followed fast and followed faster till his
songs one burden bore—
Till the dirges of his Hope that melancholy
burden bore
Of 'Never—nevermore'."
But the Raven still beguiling all my fancy
into smiling,
Straight I wheeled a cushioned seat in front
of bird, and bust and door;
Then upon the velvet sinking, I betook
myself to linking
Fancy unto fancy, thinking what this
ominous bird of yore—
What this grim, ungainly, ghastly, gaunt and
ominous bird of yore
Meant in croaking
"Nevermore."

This I sat engaged in guessing, but no


syllable expressing
To the fowl whose fiery eyes now burned
into my bosom's core;
This and more I sat divining, with my head
at ease reclining
On the cushion's velvet lining that the
lamplight gloated o'er,
But whose velvet violet lining with the
lamplight gloating o'er,
She shall press, ah,
nevermore!

Then methought the air grew denser,


perfumed from an unseen censer
Swung by Seraphim whose footfalls tinkled
on the tufted floor.
"Wretch," I cried, "thy God hath lent thee—
by these angels he hath sent thee
Respite—respite and nepenthe, from thy
memories of Lenore!
Quaff, oh quaff this kind nepenthe and
forget this lost Lenore!"
Quoth the Raven,
"Nevermore."

"Prophet!" said I, "thing of evil!—prophet


still, if bird or devil!—
Whether Tempter sent, or whether tempest
tossed thee here ashore,
Desolate yet all undaunted, on this desert
land enchanted—
On this home by horror haunted—tell me
truly, I implore—
Is there—is there balm in Gilead?—tell me—
tell me, I implore!"
Quoth the Raven,
"Nevermore."

"Prophet!" said I, "thing of evil—prophet


still, if bird or devil!
By that Heaven that bends above us—by
that God we both adore—
Tell this soul with sorrow laden if, within the
distant Aidenn,
It shall clasp a sainted maiden whom the
angels name Lenore—
Clasp a rare and radiant maiden whom the
angels name Lenore."
Quoth the Raven,
"Nevermore."

"Be that word our sign in parting, bird or


fiend," I shrieked, upstarting—
"Get thee back into the tempest and the
Night's Plutonian shore!
Leave no black plume as a token of that lie
thy soul hath spoken!
Leave my loneliness unbroken!—quit the
bust above my door!
Take thy beak from out my heart, and take
thy form from off my door!"
Quoth the Raven,
"Nevermore."

And the Raven, never flitting, still is sitting,


still is sitting
On the pallid bust of Pallas just above my
chamber door;
And his eyes have all the seeming of a
demon's that is dreaming,
And the lamplight o'er him streaming throws
his shadow on the floor;
And my soul from out that shadow that lies
floating on the floor
Shall be lifted—nevermore!
The Raven
TO ONE IN PARADISE
Thou wast all that to me, love,
For which my soul did pine—
A green isle in the sea, love,
A fountain and a shrine,
All wreathed with fairy fruits and flowers,
And all the flowers were mine.

Ah, dream to bright to last!


Ah, starry Hope! that didst arise
But to be overcast!
A voice from out the Future cries,
"On! on!"—but o'er the Past
(Dim gulf!) my spirit hovering lies
Mute, motionless, aghast!

For, alas! alas! with me


The light of Life is o'er!
"No more—no more—no more—"
(Such language holds the solemn sea
To the sands upon the shore)
Shall bloom the thunder-blasted tree
Or the stricken eagle soar!

And all my days are trances,


And all my nightly dreams
Are where thy grey eye glances,
And where thy footstep gleams—
In what ethereal dances,
By what eternal streams.
To One in Paradise
LENORE
Ah, broken is the golden bowl! the spirit
flown forever!
Let the bell toll!—a saintly soul floats on the
Stygian river;
And, Guy de Vere, hast thou no tear?—weep
now or nevermore!
See! on yon drear and rigid bier low lies thy
love, Lenore!
Come! let the burial rite be read—the
funeral song be sung!—
An anthem for the queenliest dead that ever
died so young—
A dirge for her the doubly dead in that she
died so young.

"Wretches! ye loved her for her wealth and


hated her for her pride.
And when she fell in feeble health, ye
blessed her—that she died!
How shall the ritual, then, be read?—the
requiem how be sung
By you—by yours, the evil eye,—by yours,
the slanderous tongue
That did to death the innocence that died,
and died so young?"
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like