Mathematical Methods Using Python Applications In Physics And Engineering Vasilis Pagonis Christopher W Kulp download
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
https://ebookbell.com/product/mathematical-methods-using-mathematica-
for-students-of-physics-and-related-fields-sadri-hassani-4124426
https://ebookbell.com/product/mathematical-concepts-and-methods-in-
modern-biology-using-modern-discrete-models-raina-robeva-and-terrell-
hodge-eds-4409990
https://ebookbell.com/product/mathematical-modelling-of-decision-
problems-using-the-simus-method-for-complex-scenarios-1st-edition-
nolberto-munier-35167640
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
https://ebookbell.com/product/analytic-methods-in-sports-using-
mathematics-and-statistics-to-understand-data-from-baseball-
football-2nd-edition-2nd-severini-56283544
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
https://ebookbell.com/product/practical-methods-for-optimal-control-
using-nonlinear-programming-1st-john-t-betts-1375082
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
DOI: 10.1201/9781003294320
Publisher’s note: This book has been prepared from camera-ready copy provided by the authors.
Dedication
vii
viii Contents
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.
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:
print('-'*28,'CODE OUTPUT','-'*29)
DOI: 10.1201/9781003294320-1 1
2 Mathematical Methods using Python: Applications in Physics and Engineering
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.
Solution:
print('-'*28,'CODE OUTPUT','-'*29,'\n')
Introduction to Python 3
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.
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.
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')
print('list a=',a)
a[2] = -2
print('\na[2] = -2 modifies list a into \na =',a,'\n')
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 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)
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.
(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')
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.
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')
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).
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')
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
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')
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).
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
print('-'*28,'CODE OUTPUT','-'*29,'\n')
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]
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')
from numpy import cos # method 3: import only function cos() from numpy
print('Importing just the NumPy function, result is: ', cos(0.5))
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().
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
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')
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. ]
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
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)
A = [[1 2 3]
[4 5 6]]
Data type of A is: int32
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.
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
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.
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.
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))
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]]
(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)
print('array v = ')
pp.pprint(v)
22 Mathematical Methods using Python: Applications in Physics and Engineering
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)))
array v =
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
The third element v[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]
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
plt.plot(t,y)
plt.show()
1.2
1.0
Vertical distance y(t)
0.8
0.6
0.4
0.2
0.0
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
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
plt.show()
Figure 1.2 Plot of a 3D surface z = f (x, y) from Example 1.16, using MatPlotLib.
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.
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.
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))
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
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.
print('-'*28,'CODE OUTPUT','-'*29,'\n')
f = a*sin(b*t)
deriv = diff( f,t) # evaluate symbolic derivarive of f
print('Symbolic Derivative v=dy/dt: ',deriv)
plt.plot(tims,y(tims))
plt.xlabel('Time [s]')
plt.ylabel('y(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.
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.
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:
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.
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
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.
ebookbell.com