Get Python Programming and Numerical Methods: A Guide for Engineers and Scientist 1st Edition Qingkai Kong free all chapters
Get Python Programming and Numerical Methods: A Guide for Engineers and Scientist 1st Edition Qingkai Kong free all chapters
com
https://textbookfull.com/product/python-programming-and-
numerical-methods-a-guide-for-engineers-and-scientist-1st-
edition-qingkai-kong/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/numerical-methods-for-engineers-and-
scientists-using-matlab-second-edition-esfandiari/
textboxfull.com
https://textbookfull.com/product/numerical-methods-for-
engineers-8ed-2021-8th-edition-chapra-s/
textboxfull.com
https://textbookfull.com/product/numerical-methods-for-engineers-and-
scientists-using-matlab-ramin-s-esfandiari/
textboxfull.com
Applied Numerical Methods with MATLAB for Engineers and
Scientists Fourth Edition Steven C. Chapra Dr.
https://textbookfull.com/product/applied-numerical-methods-with-
matlab-for-engineers-and-scientists-fourth-edition-steven-c-chapra-dr/
textboxfull.com
https://textbookfull.com/product/numerical-methods-in-physics-with-
python-1st-edition-alex-gezerlis/
textboxfull.com
https://textbookfull.com/product/numerical-methods-in-engineering-
with-python-1st-edition-kiusalaas-jaan/
textboxfull.com
https://textbookfull.com/product/beginning-julia-programming-for-
engineers-and-scientists-1st-edition-sandeep-nagar/
textboxfull.com
Python Programming and
Numerical Methods
A Guide for Engineers and Scientists
Qingkai Kong
Timmy Siauw
Alexandre M. Bayen
Python Programming and
Numerical Methods
A Guide for Engineers and Scientists
Academic Press is an imprint of Elsevier
125 London Wall, London EC2Y 5AS, United Kingdom
525 B Street, Suite 1650, San Diego, CA 92101, United States
50 Hampshire Street, 5th Floor, Cambridge, MA 02139, United States
The Boulevard, Langford Lane, Kidlington, Oxford OX5 1GB, United Kingdom
Copyright © 2021 Elsevier Inc. All rights reserved.
ISBN: 978-0-12-819549-9
List of Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
List of Figures
Fig. 1.1 The Miniconda download page; choose the installer based on your operating system. 4
Fig. 1.2 Screen shot of running the installer in a terminal. 5
Fig. 1.3 The default installation location of your file system. 5
Fig. 1.4 Quick way to check if Miniconda was installed successfully and the programs are run properly. 6
Fig. 1.5 Installation process for the packages that will be used in the rest of the book. 6
Fig. 1.6 Run “Hello World” in IPython shell by typing the command. “print” is a function that is
discussed later in the book that will print out anything within the parentheses. 7
Fig. 1.7 Example of a Python script file example using Visual Studio Code. Type in the commands you
want to execute and save the file with a proper name. 8
Fig. 1.8 To run the Python script from command line, type “python hello_world.py”. This line tells
Python to execute the commands that saved in this file. 8
Fig. 1.9 To launch a Jupyter notebook server, type jupyter notebook in the command line, which
will open a browser page as shown here. Click the “New” button on the top right and choose
“Python3”. This will create a Python notebook from which to run Python code. 9
Fig. 1.10 To run the Hello World example within Jupyter notebook, type the command in the code cell
(the grey boxes) and press Shift + Enter to execute it. 10
Fig. 1.11 An example demonstrating the interactive search for functions within IPython by typing TAB
after the dot. The grey box shown all available functions. 12
Fig. 1.12 The help document of pip after executing pip help. 16
Fig. 1.13 Using pip list to show all the packages installed on your machine. 17
Fig. 1.14 Using pip show to get detailed information about a installed package. 17
Fig. 1.15 The Jupyter notebook dashboard after launching the server. Red arrows (light grey arrows in
print version) are pointing to you the most common features in the dashboard. 19
Fig. 1.16 A quick view of a notebook. The Header of the notebook shows the name of the notebook. The
menu has various drop-down lists that let you access to all the functionalities of the notebook.
The tool bar provides you some shortcuts for the commonly used functionalities. 20
Fig. 1.17 Truth tables for the logical and/or. 22
Fig. 1.18 Truth tables for the logical XOR. 25
Fig. 2.1 String index for the example of "Hello World". 31
Fig. 2.2 Example of list index. 36
Fig. 5.1 Interrupt the kernel by pressing the little square. 99
Fig. 6.1 Recursion tree for factorial(3). 107
Fig. 6.2 Recursion tree for factorial(5). 108
Fig. 6.3 Illustration of the Tower of Hanoi: In eight steps, all disks are transported from pole 1 to pole 3,
one at a time, by moving only the disk at the top of the current stack, and placing only smaller
disks on top of larger disks. 111
Fig. 6.4 Breakdown of one iteration of the recursive solution of the Tower of Hanoi problem. 111
Fig. 6.5 Pascal’s triangle. 118
Fig. 8.1 Illustration of running time for complexity log(n), n, and n2 . 138
xv
xvi List of Figures
PURPOSE
Because programming has become an essential component of engineering, science, medicine, media,
business, finance, and many other fields, it is important for scientists and engineers to have a basic
foundation in computer programming to be competitive. This book introduces programming to students
from a wide range of backgrounds and gives them programming and mathematical tools that will be
useful throughout their careers.
For the most part, this book follows the standard material taught at the University of California,
Berkeley, in the class E7: Introduction to computer programming for scientists and engineers. This
class is taken by most science and engineering freshmen in the College of Engineering, and by un-
dergraduate students from other disciplines, including physics, biology, Earth, and cognitive sciences.
The course was originally taught in Matlab, but with the recent trend of the data science movement at
Berkeley, the Division of Data Sciences agreed on and supported the transform of this course into a
Python-oriented course to prepare students from different fields for further data science courses. The
course has two fundamental goals:
• Teach Python programming to science and engineering students who do not have prior exposure to
programming.
• Introduce a variety of numerical analysis tools that are useful for solving science and engineering
problems.
These two goals are reflected in the two parts of this book:
This book is written based on the book An Introduction to MATLAB® Programming and Numerical
Methods for Engineers by Timmy Siauw and Alexandre Bayen. The current book was first written in
Jupyter Notebook for interactive purposes, and then converted to LaTeX. Most of the codes showing
in this book are from the Jupyter Notebook code cells, which can be run directly in the notebook cell.
All the Jupyter Notebook codes can be found at pythonnumericalmethods.berkeley.edu.
Because this book covers such a wide range of topics, no topic is covered in great depth. Each
chapter has been designed to be covered in at most two lecture hours, even though there are entire
semester courses dedicated to these same chapters. Rather than an in-depth treatment, this book is
intended to give students a wide breadth of programming knowledge and mathematical vocabulary on
which they can expand.
We believe that just like learning a new foreign language, learning to program can be fun and
illuminating. We hope that as you journey through this book, you will agree.
xix
xx Preface
PREREQUISITES
This book is designed to introduce programming and numerical methods to students who have abso-
lutely no prior experience with computer programming. We hope this underlying concept is reflected
in the pace, tone, and content of the text. For the purpose of programming, we assume the reader has
the following prerequisite knowledge:
• Understanding of the computer monitor and keyboard/mouse input devices
• Understanding of the folder structure used to store files in most operating systems
For the mathematical portions of the text, we assume the reader has the following prerequisite
knowledge:
• High school level algebra and trigonometry
• Introductory, college-level calculus
That’s it! Anything in the text that assumes more than this level of knowledge is our mistake, and
we apologize in advance for any confusion of instances where concepts are unclear.
ORGANIZATION
Part 1 teaches the fundamental concepts of programming. Chapter 1 introduces the reader to Python
and Jupyter Notebook. Chapters 2 through 7 teach the fundamentals of programming. Proficiency in
the material from these chapters should provide enough background to enable you to program almost
anything you imagine. Chapter 8 provides the theory that characterizes computer programs based on
how fast they run, and Chapter 9 gives insights into how computers represent numbers and their effect
on arithmetic. Chapter 10 provides useful tips on good programming practices to limit mistakes from
popping up in computer code, and tells the user how to find them when they do. Chapter 11 explains
how to store data over the long term and how to make results from Python useful outside of Python
(i.e., for other programs). Chapter 12 introduces Python’s graphical features that allow you to produce
plots and charts, which is a really useful feature for engineers and scientists to visualize results. Fi-
nally, Chapter 13 introduces basics about the parallel programming in Python to take advantage of the
multicore design of today’s computers.
Part 2 gives an overview of a variety of numerical methods that are useful for engineers. Chapter 14
gives a crash course in linear algebra. Although theoretical in nature, linear algebra is the single most
critical concept for understanding many advanced engineering topics. Chapter 15 discusses eigenval-
ues and eigenvectors, which are important tools in engineering and science, and the ways we can utilize
them. Chapter 16 is about regression, a mathematical term that is simply a method of fitting theoretical
models to observed data. Chapter 17 is about inferring the value of a function between data points, a
framework known as “interpolation.” Chapter 18 introduces the idea of approximating functions with
polynomials, which can be useful for simplifying complicated functions. Chapter 19 teaches two algo-
rithms for finding roots of functions, that is, finding an x such that f (x) = 0, where f is a function.
Chapters 20 and 21 cover methods of approximating the derivative and integral of a function, respec-
tively. Chapters 22 and Chapter 23 introduce a mathematical model type called “ordinary differential
equations.” These two chapters focus on different problems, i.e., initial value problems and bound-
How to Read This Book? xxi
ary value problems, and present several methods for finding their solutions. Chapter 24 introduces the
concepts of “discrete Fourier transform” and “fast Fourier transform” and their use in digital signal
processing.
track and from being inundated by extraneous information. You may discover solutions that differ from
the text’s solutions but solve the problem just the same or even better! We encourage you to find these
alternative methods, and use your own judgment to given the tools we have provided herein to decide
which way is better.
We hope you enjoy the book!
WHY PYTHON?
Python is a high-level and general-purpose computer language that lends itself to many applications.
As it is beginner friendly, we hope that you will find it easy to learn and that it is fun to play with it.
The language itself is very flexible, which means that there are no hard rules on how to build features,
and you will find that there are several ways to solve the same problem. Perhaps its great strength is
that it has a great user community that supports it, with lots of packages to essentially plug in and go
with very little efforts. With the ongoing popular trend, Python suits the goals of data science today.
Python is free (open source), and most of the packages are also free for use. The idea of an open source
programming language makes a huge difference in the learning curve. Not only you can use these
packages for free, but also you can learn many advanced skills from the source code of these packages
developed by other users. We hope you can enjoy your learning of Python presented here and use it in
your work and life.
The first version of this book was written at a time when the standard generalist language taught in
engineering (and beyond) at UC Berkeley was Matlab. Its genesis goes back to the mid-2000s, which
precede the current era of data science, machine learning, in which Python emerged as a commonly
used language across the engineering profession. The first version was thus written as part of the E7
class at UC Berkeley, which introduces many students to programming and numerical analysis. It
would never have been written without the help of colleagues, teams of Graduate Student Instructors
(GSI), graders, and administrative staff members who helped us through the challenging process of
teaching E7 to several hundreds of students each semester at UC Berkeley. Furthermore, the first edi-
tion of this book would never have reached completion without the help of the students who had the
patience to read the book and give us their feedback. In the process of teaching E7 numerous times,
we have interacted with thousands of students, dozens of GSIs and graders, and a dozen colleagues
and administrators, and we apologize to those we will inevitably forget given the number of people
involved. We are extremely grateful for guidance from our colleagues Professors Panos Papadopou-
los, Roberto Horowitz, Michael Frenklach, Andy Packard, Tad Patzek, Jamie Rector, Raja Sengupta,
Mike Cassidy, and Samer Madanat. We owe thanks particularly to Professors Roberto Horowitz, Andy
Packard, Sanjay Govindjee, and Tad Patzek for sharing the material they used for the class, which
contributed to the material in this book. We also thank Professors Rob Harley and Sanjay Govindjee
for using a draft of this book during the semesters they taught E7 and giving us feedback that helped
improve the manuscript. The smooth running of the semester course gave the authors the time and
energy to produce this book. Managing the course was greatly facilitated by numerous administrative
staff members who bore much of the logistic load. We are particularly grateful to Joan Chamberlain,
Shelley Okimoto, Jenna Tower, and Donna Craig. Civil and Environmental Engineering Vice Chair
Bill Nazaroff deserves particular recognition for assigning the second author to teach the class in 2011.
Without this assignment the two authors of this book would not have had an opportunity to work to-
gether and write this book. E7 is notoriously the hardest class to teach at UC Berkeley in the College
of Engineering. However, it continued to run smoothly over the many semesters we learned to teach
this class, mainly due to the help of the talented GSIs we had the pleasure of working with. During the
years the coauthors taught the class, a series of legendary head GSIs have contributed to shaping the
class and making it a meaningful experience for students. In particular, Scott Payne, James Lew, Claire
Saint-Pierre, Kristen Parish, Brian McDonald, and Travis Walter have in their respective roles led a
team of dedicated GSI to exceed expectations. The GSI and grader team during the Spring of 2011
greatly influenced the material of this book. For their contribution during that critical semester, we
thank Jon Beard, Leah Anderson, Marc Lipoff, Sebastien Blandin, Sam Chiu, Rob Hansen, Jiangchuan
Huang, Brad Adams, Ryan Swick, Pranthik Samal, Matthieu Lewandowski, and Romain Bourcier. We
are also grateful to Claire Johnson and Katherine Mellis for finding errors in the text and helping us
incorporate edits into the manuscript. We are indebted to the E7 students for their patience with us
and their thorough reading of the material. Having seen thousands of them through the years, we are
sorry to only be able to mention a few for their extraordinary feedback and performance: Gursham-
njot Singh, Sabrina Nicolle Atienza, Yi Lu, Nicole Schauser, Harrison Lee, Don Mai, Robin Parrish,
xxiii
xxiv Acknowledgements
and Mara Minner. In 2018, as the UC Berkeley campus was already deeply engaged in the transition
leading to the birth of the Division of Computing, Data Science, and Society, numerous conversations
started on the need for UC Berkeley students to learn Python, which in the mean time had become
a commodity of choice for employment in most tech companies. Thus, this book started with the in-
tention of preparing engineering and science students with basic data science tools. The UC Berkeley
Division of Computing, Data Science, and Society played an active role in creating this book for a lower
division course to prepare students for further study. We thank Cathryn Carson and David Culler for
their support in writing this book and for the discussions on how to make it better. Their help happened
in parallel to the herculean efforts they led to build the Division of Computing, Data Science, and So-
ciety. It is one of the many expressions of their scientific generosity and dedication to building a rich
and innovative data science environment at UC Berkeley. Finally, we also appreciate the care and help
from Eric Van Dusen and Keeley Takimoto. About two thirds of the book are adapted from the original
Matlab version – An Introduction to MATLAB® Programming and Numerical Methods for Engineers
by the two last authors. We thank Jennifer Grannen, Brian Mickel, Nick Bourlier, and Austin Chang
for their help to convert some of the Matlab code to Python. We are (again!) grateful to Claire Johnson
for her help with the second version of the book, and to Jennifer Taggart for finding errors in the text
and helping us incorporate edits into the manuscript. We also thank the Berkeley Seismsology Lab for
the support of writing this book and the Python training over the years.
Qingkai Kong
Timmy Siauw
Alexandre M. Bayen
June 2020
CHAPTER
PYTHON BASICS
1
CONTENTS
1.1 Getting Started With Python ......................................................................................... 3
1.1.1 Setting Up Your Working Environment ............................................................. 3
1.1.2 Three Ways to Run Python Code .................................................................... 7
1.2 Python as a Calculator ............................................................................................... 9
1.3 Managing Packages .................................................................................................. 15
1.3.1 Managing Packages Using Package Managers .................................................... 15
Install a Package ............................................................................................. 15
Upgrade a Package.......................................................................................... 16
Uninstall a Package.......................................................................................... 16
Other Useful Commands ................................................................................... 16
1.3.2 Install Packages From Source ....................................................................... 18
1.4 Introduction to Jupyter Notebook ................................................................................... 18
1.4.1 Starting the Jupyter Notebook....................................................................... 18
1.4.2 Within the Notebook .................................................................................. 19
1.4.3 How Do I Close a Notebook?......................................................................... 20
1.4.4 Shutting Down the Jupyter Notebook Server ...................................................... 20
1.5 Logical Expressions and Operators ................................................................................ 20
1.6 Summary and Problems .............................................................................................. 23
1.6.1 Summary ............................................................................................... 23
1.6.2 Problems ............................................................................................... 23
1 https://www.anaconda.com/download/.
2 https://conda.io/miniconda.html.
FIGURE 1.1
The Miniconda download page; choose the installer based on your operating system.
In this example, we will use Mac OS X to show you how to install Miniconda (the process of which
is very similar to installing on Linux). For Windows users, please skip the rest of this section and read
Appendix A on the installation instructions. The main differences between Anaconda and Miniconda
are as follows:
• Anaconda is a complete distribution framework that includes the Python interpreter, package man-
ager, and the commonly used packages in scientific computing.
• Miniconda is a “light” version of Anaconda that does not include the commonly used packages.
You need to install all the different packages yourself, but it does include the Python interpreter and
package manager.
The option we’ve chosen here is Miniconda, and we will install only those packages that we will
need. The Miniconda install process is described below:
Step 1. Download the Miniconda installer from the website.3 The download page is shown in
Fig. 1.1. Here you can choose a different installer based on your OS. In this example, we choose Mac
OS X and Python 3.7.
Step 2. Open a terminal (on a Mac, you can search for “terminal” in Spotlight search). Run the
installer from the terminal using the commands showing in Fig. 1.2. After you run the installer, follow
the guide to finish the installation.
Note that although you can change the installation location by giving it an alternative location on
your machine, the default is your home directory (Fig. 1.3).
After installation, you can check the installed packages by typing the commands shown in Fig. 1.4.
3 https://conda.io/miniconda.html.
1.1 GETTING STARTED WITH PYTHON 5
FIGURE 1.2
Screen shot of running the installer in a terminal.
FIGURE 1.3
The default installation location of your file system.
6 CHAPTER 1 PYTHON BASICS
FIGURE 1.4
Quick way to check if Miniconda was installed successfully and the programs are run properly.
FIGURE 1.5
Installation process for the packages that will be used in the rest of the book.
1.1 GETTING STARTED WITH PYTHON 7
Step 3. As shown in Fig. 1.5, install the basic packages used in this book: ipython, numpy, scipy,
pandas, matplotlib, and jupyter notebook. In a later section, we will talk about the management of
the packages using pip and conda.
FIGURE 1.6
Run “Hello World” in IPython shell by typing the command. “print” is a function that is discussed later in the book
that will print out anything within the parentheses.
8 CHAPTER 1 PYTHON BASICS
FIGURE 1.7
Example of a Python script file example using Visual Studio Code. Type in the commands you want to execute and
save the file with a proper name.
FIGURE 1.8
To run the Python script from command line, type “python hello_world.py”. This line tells Python to execute the
commands that saved in this file.
Visual Studio Code4 ) to type the commands you wish to execute in a file called hello_world.py, as
shown in Fig. 1.7, which is then run from terminal (see Fig. 1.8).
4 https://code.visualstudio.com.
1.2 PYTHON AS A CALCULATOR 9
FIGURE 1.9
To launch a Jupyter notebook server, type jupyter notebook in the command line, which will open a browser
page as shown here. Click the “New” button on the top right and choose “Python3”. This will create a Python
notebook from which to run Python code.
Using Jupyter Notebook. The third way to run Python is through Jupyter Notebook, which is a very
powerful browser-based Python environment. We will discuss this in details later in this chapter. The
example presented here is to demonstrate how quickly we can run the code using Jupyter notebook.
If you type jupyter notebook in the terminal, a local web page will pop up; use the upper right button
to create a new Python3 notebook, as shown in Fig. 1.9.
Running code in Jupyter notebook is easy. Type your code in the cell and press Shift + Enter
to run the cell; the results will be shown below the code (Fig. 1.10).
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com