Introduction To Python For Engineers and
Introduction To Python For Engineers and
to Python for
Engineers and
Scientists
Open Source Solutions for Numerical
Computation
—
Sandeep Nagar
Introduction to
Python for Engineers
and Scientists
Open Source Solutions for
Numerical Computation
Sandeep Nagar
Introduction to Python for Engineers and Scientists: Open Source Solutions
for Numerical Computation
Sandeep Nagar
New York, USA
v
TABLE OF CONTENTS
vi
TABLE OF CONTENTS
vii
TABLE OF CONTENTS
Chapter 6: Arrays��������������������������������������������������������������������������������87
6.1 Introduction ...................................................................................................87
6.2 numpy ...........................................................................................................88
6.3 ndarray ..........................................................................................................89
6.4 Automatic Creation of Arrays ........................................................................92
6.4.1 zeros( ) ..................................................................................................92
6.4.2 ones( ) ...................................................................................................93
6.4.3 ones_like( ) ...........................................................................................94
6.4.4 empty( ) .................................................................................................94
6.4.5 empty_like( ) .........................................................................................95
6.4.6 eye( ) .....................................................................................................95
6.4.7 identity( ) ...............................................................................................97
6.4.8 full( ) ......................................................................................................98
6.4.9 full_like( ) ..............................................................................................98
6.4.10 Random Numbers ...............................................................................99
6.5 Numerical Ranges .......................................................................................106
6.5.1 A Range of Numbers ...........................................................................106
6.5.2 Linearly Spaced Numbers ..................................................................107
6.5.3 Logarithmically Spaced Numbers.......................................................108
6.5.4 meshgrid( ) ..........................................................................................108
6.5.5 mgrid() and ogrid()..............................................................................109
6.6 tile( ) ............................................................................................................111
6.7 Broadcasting ...............................................................................................112
6.8 Extracting Diagonal .....................................................................................114
viii
TABLE OF CONTENTS
Chapter 7: Plotting����������������������������������������������������������������������������133
7.1 Introduction .................................................................................................133
7.2 matplotlib ....................................................................................................134
7.2.1 pylab vs. pyplot...................................................................................135
7.3 Plotting Basic Plots .....................................................................................136
7.3.1 Plotting More than One Graph on Same Axes .....................................139
7.3.2 Various Features of a Plot ...................................................................140
7.4 Setting Up to Properties ..............................................................................147
7.5 Histograms ..................................................................................................147
7.6 Bar Charts ...................................................................................................149
7.7 Error Bar Charts ..........................................................................................152
ix
TABLE OF CONTENTS
x
TABLE OF CONTENTS
xi
TABLE OF CONTENTS
Index �������������������������������������������������������������������������������������������������247
xii
About the Author
Sandeep Nagar, PhD (Material Science, KTH,
Sweden) teaches and consults on the use
of Python and other open source software
for data science/analysis. In addition to
teaching at universities, he frequently gives
workshops covering open source software
and is interested in developing hardware for
scientific experiments.
xiii
About the Technical Reviewer
Michael Thomas has worked in software
development for more than 20 years as an
individual contributor, team lead, program
manager, and vice president of engineering.
Michael has more than 10 years of experience
working with mobile devices. His current
focus is using mobile devices to accelerate
information transfer between patients and
health care providers in the medical sector.
xv
Acknowledgments
I wish to thank Steve, Mark, and the whole team at Apress for bringing out
this book in such a nice format. I also wish to thank the Python community
for answering questions on forums, which helped me understand difficult
concepts.
xvii
CHAPTER 1
Philosophy of Python
1.1 Introduction
Python emerged as a leader [1] among well-established and optimized
languages including C, C++, and Java for very simple reasons. Python
incorporates the principles of the philosophy that complex tasks can be
done in simple ways. We tend to think that real-world, complex problems
need complex pathways to produce complex solutions. The developers
of Python embraced the exact opposite philosophy. Python was created
to have an extremely fast and simple learning curve and development
process for software engineers. As a result, it is considered the most
general-purpose programming language since users can work in almost
any study domain and still be able to find a useful piece of code for
themselves. Python harnessed the power of the open source movement,
which helped it amass a huge user base from virtually all walks of life.
Being open source in nature, Python allowed people to make small
programs and share them with each other with ease. In Python, a group
of programs for performing various tasks makes up a module (package).
At the time of writing, there are over 117,181 [2] modules that have been
submitted by an even larger number of developers around the world. The
large number of modules and developers has allowed Python’s use to
jump rapidly within the computer science community and finally grab the
number-one position as the most favored [1] programming language.
2
Chapter 1 philosophy of python
• A searchable history
• Tab completion
3
Chapter 1 philosophy of python
4
Chapter 1 philosophy of python
5
Chapter 1 philosophy of python
• Readability counts.
6
Chapter 1 philosophy of python
1.1.6 Portability
Since Python belongs to an open source community, it has been ported
(that is, adapted to work on) to many many platforms so that Python
code written on one platform can run without modification on others
(except system-dependent features). Python has been posted for popular
operating systems including Linux, Windows, Macintosh, Solaris, and Sony
PlayStation.
1.1.7 Extensibility
Rather than providing all functionalities in its core program, Python’s
creators designed it to be highly extensible. Users can thus choose to
have functionality as per their requirements. For example, if a user needs
to work on differential equations, then that user can use a module for
differential equations rather than all users having that functionality but
7
Chapter 1 philosophy of python
never using it. Python can also be embedded in existing applications that
need a programmable interface.
Python programs can be embedded into other programs written in
programming languages such as Julia, C, C++, and so on. Furthermore,
other programming language codes can be embedded into Python.
This feature has enabled the use of a lot of legacy code written in other
languages and already optimized for speed and stability, thus avoiding the
replication of efforts and hereby tremendously increasing the productivity
of an organization. Hence, Python has been embraced with open arms by
industry and academia alike.
1.2 History
The development of the Python programming language dates back to the
1980s. Guido van Rossum at CWI in the Netherlands began implementing
it in December 1989. This was an era when computing devices were
becoming increasingly powerful and reliable with every advancing day.
Van Rossum named the language after the BBC TV show Monty Python’s
Flying Circus. Python 1.0 was released to the public in 1994, Python 2.0 in
2000, and Python 3.0 in 2008. Howver, Python 3 was not created to be
backward compatible with Python 2, which made it less practical for users
who were already developing with Python 2. As a result, a lot of developers
have continued using Python 2, even now. Nonetheless, the future belongs
to Python 3, which has been developed in a more efficient manner. Hence,
we will discuss Python-3-based codes in this book.
8
Chapter 1 philosophy of python
You can understand the technical details of their differences when you
understand their basic structures and basic usage.
9
Chapter 1 philosophy of python
10
Chapter 1 philosophy of python
1.5 Summary
Python has gained a lot of attention worldwide owing to its flat learning
and steep development curves. It has gained the number-one spot in
recent times in terms of popularity of programming languages. Owing
to a large base of developers due to its open source model, Python has
achieved a rich library of modules for various tasks required to solve many
engineering problems. Hence, Python-educated engineers can fulfill the
demands of modern industry, which demands fast and efficient solutions
to its problems.
1.6 Bibliography
[1] https://spectrum.ieee.org/computing/
software/the-2017-top-programming-languages.
[2] https://pypi.python.org/pypi.
11
Chapter 1 philosophy of python
[3] https://www.python.org/dev/peps/pep-0020/.
[4] https://wiki.python.org/moin/PortingToPy3k/
BilingualQuickRef.
[5] https://docs.python.org/3/howto/pyporting.
html.
[6] https://micropython.org/.
12
CHAPTER 2
Introduction to
Python Basics
2.1 Introduction
The best way to learn Python is to try Python on the Python interpreter. In
this chapter, we will illustrate how to install and use the Python interpreter.
Installation can be done on all popular operating systems. As examples, we
will demonstrate installion on Windows, Ubuntu (Linux), and Mac OS X.
2.2 Installation
The Python interpreter has been provided for a variety of platforms. An
operating system defines a scheme to store files and run codes in a specific
manner. These different schemes require different settings of the Python
interpreter so that it can be compatible with the host it uses for computing
resources. The three most popular choices for operating systems are
Windows, Linux, and Mac OS X. While the Python interpreter comes
pre-installed in Linux and Mac OS X, a Windows operating system would
need a separate installation software. The Python community’s web site [1]
provides the primary means of knowing the progress in this domain. It also
provides the authentic downloads [2] of source code for installation.
2.2.1 Windows
Users can download a 32-bit or a 64-bit installer file as per the system’s
configurations and simply click it to start the installation process. As soon
as it is finished, a symbol in the applications installation appears. When
this symbol is double-clicked, it opens the Python shell (Figure 2-1), which
is a program that runs the Python interpreter.
14
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
The downloaded IDLE also provides an option for a text editor that
can run scripts. Alternatively, if you have properly defined the path of the
interpreter to the system, you can simply open the terminal and type the
following:
1 $python hello.py
Here we are assuming that you wish to run a Python program named
hello.py. (All Python programs are saved with the extension .py.)
We suggest learning the usage of the Python terminal for interactive
programming and executing multiline codes in the manner previously
discussed. Henceforth, the code written at the Python prompt (>>>) will
signify that it is being written line-by-line and being executed in a similar
fashion so that the programmer is working interactively at the Python
prompt. The .py files used in this book are executed at the system’s
terminal.
2.2.2 Ubuntu
The Python interpreter is pre-installed in almost all Linux distributions.
We will look at an example of Ubuntu Linux System here. The Python
3 interpreter can be called from a Linux command terminal by typing
python3 and pressing Enter. The terminal goes to the Python interpreter
session (Figure 2-2) where the programmer can type python expressions.
15
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
2.2.3 Mac OS X
Mac OS X works in the same way as all Linux distributions. The Python
interpreter comes pre-installed. You can start the Python interpreter
session by simply typing python3 on the terminal. (See Figure 2-3.)
16
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
17
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
./hello
The user can share the object file and, if the microprocessor
architecture is the same as that of another user, it will be executed
uniformly. If, however, the architecture of the machine is different, the
source code must first be compiled for the target machine and then made
to execute.
18
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
In just one line, an interpreter scans the world print and looks for
what it means. In the Python interpreter, it means to print to a particular
device. A device can be a computer terminal, printer plotter, and so forth.
By default, it is a computer terminal. The print command also demands
arguments that are scanned in the second step as a string hello world.
(A string in Python can be enclosed in ” or ””). Hence, the complete
interpretation of the line is to print the string hello world on a computer
terminal.
When a program composes hundreds and thousands of lines, a
compilation process will yield a faster result because the object code needs
to be only compiled once and then run directly on a microprocessor. An
interpreted code will check for interpretations each time it needs to be
processed. On the other hand, even a single syntax error will not let the
compilation process complete, resulting in compilation error. Conversely,
a Python interpreter will interpret the Python code up to the point where
any kind of error is encountered.
Despite its being inherently slow, Python has become a favorite among
scientists and engineers for being extremely simple, intuitive, and powerful
due to its rich library of modules for various computational tasks.
19
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
20
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
1. Editor
– Variable Explorer
21
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
– File Explorer
– Help
1 >>>2+4
2 6
3 >>>2.+4
4 6.0
5 >>>2.0+4
6 6.0
7 >>>2.0+4.
8 6.0
9 >>>2.0+4.0
10 6.0
22
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
23
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
2.6 Modules
Python Multiverse has expanded with thousands of modules and, being
open source, most of them are readily available. Modules are collections
of Python programs for accomplishing specific tasks. For example, numpy
has various facilities for numerical computation. It was further expanded
into scipy for scientific computation in general. matplotlib is an acronym
for mathematical plotting library, which has rich features for plotting a
variety of publication-ready graphs. pandas is the library for data analysis,
scikit-learn for machine learning, scikit-image for image processing,
and sympy for symbolic computing.
To use a module, it must be installed in the machine first. Installation
includes downloading the files into an appropriate folder or directory,
unzipping them, and defining proper paths. There is an easier way
for Ubuntu users where the short command-line-based program pip
performs these tasks seamlessly.
Running the simple command
installs the program pip first. It can then be used to install a package, say
numpy, by simply issuing the command
Replacing the name of the package with the desired package will
do the trick of installing the packages hassle-free. Also, modules can be
upgraded to the latest version by typing
24
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
Installing scipy stack [4] is very useful for our purposes because it
installs a variety of programs that we will be using. It can be installed by
issuing the following command on an Ubuntu terminal:
Anaconda IDE comes pre-installed with all the modules this book
requires. Any extra modules can be installed in a similar manner using a
conda terminal. To open a conda terminal, first click Environments and
then the arrow button next to root (Figure 2-6). You can choose the option
Open Terminal to open a Linux-like terminal in any operating system.
25
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
import math
26
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
This command imports the module named math and all its objects are
now available for usage. The procedure to use them is as follows:
1. import math
27
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
1 $cd my_project_folder
2 $virtualenv proj1
The second command will create a folder in the current directory. This
folder will contain the Python executable files and a copy of the pip library,
which you can use to install other packages.
28
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
1 $source proj1/bin/activate
1 $deactivate
29
CHAPTER 2 INTRODUCTION TO PYTHON BASICS
The command puts the developer back to the system’s default Python
interpreter with all its installed libraries. In case developers need to
remove the virtual environment, they can remove its folder by issuing the
following command:
1 $rm − rf proj1
2.8 Summary
Python has an extremely flat learning curve owing to its interpretive
language, which can be used to insert instructions line-by-line and run
them subsequently. This methods avoids compilation and subsequent
errors that are major stumbling blocks for a beginner who has limited
knowledge of the inner workings of the programming language. Being
open source in nature, the Python interpreter can be downloaded for free
from the Internet. Anaconda IDE presents a good integrated development
environment for Python developers, and we recommend that you use it for
practicing the codes in this book.
2.9 Bibliography
[1] https://www.python.org/.
[2] https://www.python.org/downloads/.
[3] https://www.anaconda.com/download/.
[4] https://www.scipy.org/stackspec.html.
30
CHAPTER 3
IPython
3.1 Introduction
The biggest challenge the creators of a programming language face is
attracting developers and making them want to learn the language. Usually
developers use documentation or help books to gain insights into the
language, but an interactive environment allows developers to experiment
with commands and programs as they learn. This environment has already
been provided by Python’s interactive shell.
Another option for providing the same environment is IPython [1].
IPython was inspired [2] by the notebook environments of Maple and
Mathematica. It launched in 2001 and immediately started attracting
developers since it conceptualized a simple and intuitive environment to
execute Python code with the following features:
Since 2001, the IPython environment has grown tremendously and the
popular web-browser-based interactive environment has even changed
its name to Jupyter Notebook [3] to highlight the fact that, in addition
to Python, it can run other kernels. At the time of writing, it supports 40
programming languages including Julia, Python, Scala, R, C, and C++.
Jupyter needs a native installation of the Python interpreter to work, so users
must install the Python interpreter as illustrated in Chapter 2 and then they
can work within the IPython environment with Python as one of its kernel.
32
CHAPTER 3 IPYTHON
1 $ipython
33
CHAPTER 3 IPYTHON
the IPython prompt running the IPython REPL is waiting for the user to
type the first input. When you type an input and execute the expression
by pressing the Enter key, you obtain output with the prompt Out[1],
signifying it is output of the first Python expression at In[1]. The numbers
within parentheses keep increasing by one, which makes it useful while
teaching Python as well as when tracking workflow during a session. These
numbers get reset once a session has restarted.
The IPython shell also supports Unix/Linux system commands. Some
sets of useful commands are the following:
• cd.. and cd
– The command cd.. enables a user to step one step back in the
directory tree structure.
– The command cd places a user in the home directory.
34
CHAPTER 3 IPYTHON
• %history
• %lsmagic
• %magic
• %run
• %time
35
CHAPTER 3 IPYTHON
comments can be inserted for each line of code. It is good practice to insert
useful comments to yourself in case you revisit the code after a long time
or if you share the code for a project so that others can understand the
logic behind the usage of commands in the given code file:
36
CHAPTER 3 IPYTHON
37
CHAPTER 3 IPYTHON
38
CHAPTER 3 IPYTHON
browsers are supported for this case. This book uses Google Chrome
(Version 60.0.3112.113 (Official Build) (64-bit)) for the purpose of testing
the code used henceforth.
The web browser window will list the directories and files in the home
folder. Users can navigate to a target directory and start a Jupyter session
for Python 3. They can click the New button and choose a kernel (Python3
in this case). This will open a screen similar to Figure 3-3.
39
CHAPTER 3 IPYTHON
• Naming a notebook
• Cells
• Code
40
CHAPTER 3 IPYTHON
• Raw NBConvert
41
CHAPTER 3 IPYTHON
• Heading
Users learn best to use the Jupyter Notebook by trying it. A sample
notebook is shown in Figure 3-4.
42
CHAPTER 3 IPYTHON
details in markdown cell types. The markdown cell types enable writing
mathematical equations using LaTeX commands.
Users can also save the Jupyter Notebook as a .py file (Python program
to be executed at the Python interpreter). Here all cells except the code
cells are converted as comments by adding the symbol # at the start.
Jupyter Notebooks can be saved in an HTML format to be used
when embedding them on a web site. This is useful for online course
development. They can also be saved as LaTeX files to be built in a
particular format or directly as a PDF document.
The saved files can then be shared with people who wish to learn a
particular topic. Users can simply run the notebook within the Jupyter
Notebook environment. This feature benefits classroom teaching
quite a lot. The teacher and students can execute their Jupyter Notebooks
cell-by-cell and understand the concepts in an easier fashion. Otherwise,
a teacher would have to switch between a presentation file and the Python
interpreter for a Python teaching session. Users can also define a test as
well as assignments using this facility.
43
CHAPTER 3 IPYTHON
The online session has a sample notebook for a list of languages. Users
can use the sample Python Notebook to learn the basics. Users can create a
directory and then use it to store all the Jupyter Notebooks in an organized
fashion. These notebooks can be downloaded on a local machine and
can be used in a local Jupyter Notebook session. Users can perform the
opposite action too. In other words, they can load a local Jupyter Notebook
on an online session using the Upload button in the top-left menu.
3.6 Summary
In this chapter, we have illustrated working in an IPython and Jupyter
Notebook environment. Jupyter Notebook is increasingly being used by
developers to propagate knowledge to a wider audience since users can
package the code and illustrative descriptions in one single file. Thousands
of Jupyter Notebooks exist on various web sites, enabling the number of
Python users to multiply at an exponential rate. We suggest that users of
44
CHAPTER 3 IPYTHON
this book should also make a separate Jupyter Notebook for each chapter
for their own understanding and release it on the Internet for the benefit of
others.
3.7 Bibliography
[1] F. Pérez and B. E. Granger, “IPython: A system for
interactive scientific computing,” Computing in
Science and Engineering, vol. 9, pp. 21–29, May 2007.
[2] http://blog.fperez.org/2012/01/ipython-
notebook-historical.html.
[3] https://jupyter.org/.
[4] https://ipython.org/ipython-doc/3/
interactive/magics.html.
[5] https://nbsphinx.readthedocs.io/en/0.2.3/
code-cells.html.
[6] http://markdown-guide.readthedocs.io/en/
latest/basics.html.
[7] https://try.jupyter.org/.
45
CHAPTER 4
Data Types
4.1 Introduction
The best way to take full advantage of this book is to begin working on an
IPython prompt by feeding it code and observing the output. You can use
Anaconda IDE to avoid the need to install the required packages for the
book. You can use Spyder IDE during an IPython session as well as editor
to write multiline files. We suggest that you write detailed descriptive
comments wherever needed to enhance understanding of workflow of
the given code. This scheme works uniformly across all platforms. In
this chapter, we will discuss the various kinds of data in Python and their
categorization into several data types.
Modern computers distinguish data in several types. Data can be
numbers, characters, strings (a group of characters), and so on. In Python,
you can define new data types as and when required. There are some built-
in data types for handling numbers and characters. Different data types
occupy different amounts of memory. It is important to understand your
needs and choose a data type accordingly. Data types also determine the
accuracy of the answer. We will discuss the various built-in data types in
Python in the sections that follow.
4.2 Logical
This type of data stores boolean values True or False and can be operated
by boolean operators such as AND and OR. Most programming languages
use the values 1 or 0 for boolean values, but Python differs in this
approach. Let’s explore their usage with some examples.
48
CHAPTER 4 DATA TYPES
True False
False True
1 >>> True
2 True
3 >>> False
4 False
5 >>> not True
6 False
7 >>> not False
8 True
9 >>> True and False
10 False
11 >>> True or False
12 True
13 >>> True ˆ False
14 True
15 >>> True ˆ False
16 True
49
CHAPTER 4 DATA TYPES
4.3 Numeric
Numeric: There are four types of numeric data types:
• int: Integers
• float: Floating point numbers
4.3.1 Integer
Python has arbitrary precision for float, long, and complex numbers.
As a result, the limit of the length of these numbers is subject to the
availability of memory. The positive side of this architecture is that users
are not limited to a range of numbers, but they must always ensure that
sufficient memory is available during the calculation to avoid erroneous
results. Python 2 limits the size of int to bytes (to the same size as in the
50
CHAPTER 4 DATA TYPES
1 >>> type(-1)
2 <class 'int'>
3
4 >>> type(1)
5 <class 'int'>
1 >>> type(2)
2 <class 'int'>
3 >>> type(2.0)
4 <class 'float'>
51
CHAPTER 4 DATA TYPES
• Sign (±)
52
CHAPTER 4 DATA TYPES
1. Single precision:
2. Double precision:
• Occupies 80 bits.
4. Quadruple precision:
This scheme can trade off between range and precision. While integers
have unlimited precision, floating point numbers are usually implemented
using double precision, as previously explained. The information about
the precision and internal representation of floating point numbers for the
machine on which your program is running is available in sys.float_info:
53
CHAPTER 4 DATA TYPES
1 2 3
0.123 ® 1
+ 2+ 3
10 10 10
in the number system with base 10. Conversely, in a number system with
base 2, it is represented as
1 2 3
0.123 ® + +
21 2 2 2 3
This calculation shows that 0.1232 = 0.13510. If you use more bits to store
the value, you get a better approximation of the real number, but you are
always limited to the use of approximated values instead of real values.
As sys.float_info informed, the biggest floating point number is
max = 1.7976931348623157e + 308 (1.7976931348623157 × 10308).
To employ even more precision, you can use the decimal module that
has the function Decimal(), which returns the number as stored by the
computer:
54
CHAPTER 4 DATA TYPES
1 >>> 2+3j
2 (2+3j)
3 >>> type(2+3j)
4 <class 'complex'>
5 >>> complex(2,3)
6 (2+3j)
7 >>> type(complex(2,3))
8 <class 'complex'>
55
CHAPTER 4 DATA TYPES
4.4 Sequences
Language symbols require storage on a computer and, hence, must be
defined as an object. This object is known as a character. Every individual
symbol of a language that appears on a computer screen and printed
papers is considered a character in programming languages. This includes
ASCII and Unicode characters. Examples of characters include letters,
numeral digits, whitespaces, punctuation marks, exclamation marks, and
so on. In general, all keys on a keyboard produce characters.
For the purpose of communicating between computing devices,
characters are encoded in well-defined, internationally accepted formats
(such as ASCII and UTF-8) that assign each character to a string of binary
numbers. Two examples of usual encodings are ASCII and the UTF-8
encoding for Unicode. All programming languages must be able to decode
and handle internationally accepted characters. Python also deals with
characters using data type strings, lists, and tuples.
4.4.1 Strings
A string is merely a sequence of characters. Lowercase and uppercase
characters have different encoding; thus, strings are case-sensitive:
1 >>> type('a')
2 <class 'str'>
3 >>> type('abba')
4 <class 'str'>
5 >>> type("a")
6 <class 'str'>
7 >>> type("abba")
8 <class 'str'>
56
CHAPTER 4 DATA TYPES
You can use special characters to print the characters to define spaces
and to print characters on a new line. This can be done using \t and \n
characters, which print a tab and a new-line character, respectively:
1 >>> print ("' Python can also print multiline strings having
tabs like
\t and also prints in \n next line"')
2 Python can also print multiline strings having tabs like and
also prints in
3 next line
57
CHAPTER 4 DATA TYPES
both double and single quotes as characters. This behavior can be studied
in the following code:
1 >>> [1,2.0,'a',"Alpha"]
2 [1, 2.0,'a','Alpha']
3 >>> type([1,2.0,'a ',"Alpha"])
4 <class 'list'>
1 >>> (1,2.0,'a',"Alpha")
2 (1,2.0,'a','Alpha')
3 >>> type((1,2.0,'a',"Alpha"))
4 <class 'tuple'>
58
CHAPTER 4 DATA TYPES
using their indices. More information about how this is done is discussed
in Chapter 5, where operations on lists have been defined. In scientific
computing, universal constants can be defined as a tuple and then can be
accessed in a program using its index.
1 >>> set(['h','e','l','l','o',1,2.0,3+4j])
2 {1, 2.0, 'h', 'o', (3+4j), 'l', 'e'}
3 >>> type(set(['h','e','l','l','o',1,2.0,3+4j]))
4 <class 'set'>
5 >>> frozenset(['h','e','l','l','o',1,2.0,3+4j])
6 frozenset({1, 2.0, 'h', 'o', (3+4j), 'l', 'e'})
7 >>> type(frozenset(['h','e','l','l','o',1,2.0,3+4j]))
8 <class 'frozenset'>
Please note that since l occurred two times while defining the set, it
was given only one membership. Set operations are discussed in detail in
subsequent chapters. Just like a tuple object is immutable, a frozenset is
also an immutable object and similar to a set object.
59
CHAPTER 4 DATA TYPES
4.6 Mappings
Mapping is a scheme of defining data where each element is identified
with a key called “hash tag.” The element can be accessed by referring to
the key. One of the data types in this category is a dictionary.
A dictionary is an unordered pair of values associated with keys.
These values are accessed with keys instead of an index. These keys
have to be hashable like integers, floating point numbers, strings, tuples,
and frozensets. Lists, dictionaries, and sets other than frozensets are not
hashable. Following is an example of a dictionary:
1 >>> None
2 >>> type(None)
3 <class 'NoneType'>
60
CHAPTER 4 DATA TYPES
4.8 Summary
Object-oriented programming uses the fact that all computing entities are
merely objects that interact with each other as per their defined behavior.
We have discussed some built-in data types in this chapter. Some data
types are defined inside the modules. Users can define their data types and
define their properties. Before going to these advanced topics, it will be
useful to know how operators operate on various kinds of data. This will be
the subject of Chapter 5.
4.9 Bibliography
[1] “IEEE standard for floating-point arithmetic,” IEEE
Std 754-2008, pp. 1–70, Aug 2008.
61
CHAPTER 5
Operators
5.1. Introduction
Operators work in a similar fashion to mathematical functions. They
provide a relationship between two different domains. For example, the
multiplication operator makes an ordered pair of operands (data on which
the operator works) and produces another data point. This can be done to
any number of data points. In this way, the operator transforms data from
the domain of operands to the domain of results.
The symbols for basic operators are given in Table 5-1.
Addition +
Subtraction -
Multiplication *
Division \
Modulus %
Exponentiation **
1 >>> 2+3
2 5
3 >>> 'a' + 'b'
4 'ab'
5 >>> ""hello" + " " + "world" + "!"
6 'hello world !
7 >>> 'a'∗3
8 'aaa'
9 >>> 'a'/3
10 Traceback (most recent call last):
11 File "<stdin>", line 1, in <module>
12 TypeError: unsupported operand type(s) for /: 'str' and
'int'
13 >>> 'a'%3
14 Traceback (most recent call last):
15 File "<stdin>", line 1, in <module>
16 TypeError: not all arguments converted during string
formatting
17 >>> 'a'∗∗3
18 Traceback (most recent call last):
19 File "<stdin>", line 1, in <module>
20 TypeError: unsupported operand type(s) for ∗∗ or pow():
'str and 'int'
64
CHAPTER 5 OPERATORS
1010 2 = 1´ 2 3 + 0 ´ 2 2 + 1´ 21 + 0 ´ s 0
65
CHAPTER 5 OPERATORS
11 5
12 >>> print(answer) # old value is still stored in 'answer'
13 1.2144
14 >>> answer = (a∗∗2) + (10 ∗ a) # calculation using new
values
15 >>> print(answer) # New value is printed
16 75
66
CHAPTER 5 OPERATORS
Using the module keyword, you can obtain the list of keywords using
the function keyword.kwlist. The code given in keyword.py gives a list of
keywords, which cannot be used as variable names. (See Listing 5-1.)
1 import keyword
2
3 print ("Python keywords:", keyword.kwlist)
67
CHAPTER 5 OPERATORS
A handy way of checking a name among the keywords list exists for
an interactive session. To check if a particular variable name is a keyword
or not, you can use the function keyword.iskeyword(). The name can be
input as a string to this function. As shown in the following code, if the
input string is a keyword, then the value True is returned. Otherwise, False
is returned:
1 >>>import keyword
2 >>>keyword.is keyword ('lambda')
3 True
4 >>>keyword.is keyword ('lamb')
5 False
68
CHAPTER 5 OPERATORS
• a=10
• b=a
• a=15
69
CHAPTER 5 OPERATORS
Operator Example
= v = a+b
+= v +=a ⇒ v = v + a
-= v -=a ⇒ v = v - a
/= v /=a ⇒ v = v / a
//= v //=a ⇒ v = v // a
*= v *=a ⇒ v = v * a
**= v **=a ⇒ v = v ** a
%= v %=a ⇒ v = v % a
70
CHAPTER 5 OPERATORS
71
CHAPTER 5 OPERATORS
1 >>> a = b = c = 10
2 >>> a
3 10
4 >>> b
5 10
6 >>> c
7 10
8 >>> c = 15
9 >>> a
10 10
11 >>> b
12 10
13 >>> c
14 15
15 >>> a = b = c = 15
16 >>> a
17 15
18 >>> b
19 15
20 >>> c
21 15
1 >>> a = 4.0; type(a) # a is assigned the value 4.0 and its type
is found to be floating point number
2 <class 'float'>
3 >>> a = 4; type(a) # a is assigned the value 4 and its type is
found to be integer
4 <class 'int'>
5 >>> a = 4e10;type(a) # a is assigned the value 4 X 10ˆ10 and its
type is found to be floating point number
6 <class 'float'>
7 >>> b = 'a'; type(a) # b is assigned value same as in a i.e 4 X
10ˆ10 and its type is found to be floating point number
8 <class 'float'>
9 >>> b = 'sandeep'; type(b) # b is reassigned a value as string
and its type is found to be string
10 <class 'str'>
74
CHAPTER 5 OPERATORS
75
CHAPTER 5 OPERATORS
4 [1, 2, 3, 4, 5, 6]
5 >>> 'hello' ∗3
6 'hello hello hello'
7 >>> [1,2,3] ∗ 3
8 [1, 2, 3, 1, 2, 3, 1, 2, 3]
9 >>> 'hello' ∗3.1
10 Traceback (most recent call last):
11 File "<stdin>", line 1, in <module>
12 TypeError: can't multiply sequence by non-int of type 'float'
13 >>> [1,2,3] ∗3.1
14 Traceback (most recent call last):
15 File "<stdin>", line 1, in <module>
16 TypeError: can't multiply sequence by non-int of type
'float'
17 >>> 'hello' /3
18 Traceback (most recent call last):
19 File "<stdin>", line 1, in <module>
20 TypeError: unsupported operand type(s) for /: 'str' and 'int'
21 >>> [1,2,3] // 3
22 Traceback (most recent call last):
23 File "<stdin>", line 1, in <module>
24 TypeError: unsupported operand type(s) for //: 'list' and 'int'
25 >>> 'hello' % 3
26 Traceback (most recent call last):
27 File "<stdin>", line 1, in <module>
28 TypeError: not all arguments converted during string formatting
29 >>> [1,2,3] % 3
30 Traceback (most recent call last):
31 File "<stdin>", line 1, in <module>
32 TypeError: unsupported operand type(s) for %: 'list' and 'int'
33 >>> [1,2,3] - 3
34 Traceback (most recent call last):
76
CHAPTER 5 OPERATORS
77
CHAPTER 5 OPERATORS
1. Parentheses
2. Exponents
3. Multiplication
4. Division
5. Addition
6. Subtraction
78
CHAPTER 5 OPERATORS
The result of logical operators is either one of the two binary objects aptly
named True and False. In some programming languages, binary operators
are represented as 1 and 0. They can also be compared for equality:
79
CHAPTER 5 OPERATORS
4 >>> b = False
5 >>> a and b
6 False
7 >>> a or b
8 True
9 >>>1 >= 2 == 2 >= 1
10 False
11 >>>1 >= 2
12 False
13 >>>2 >= 1
14 True
15 >>>False == True
16 False
17 >>>False > True
18 False
19 >>>False < True
20 True
80
CHAPTER 5 OPERATORS
8 True
9 >>> 10 in b
10 False
81
CHAPTER 5 OPERATORS
The binary composition of an int object can be shown using the bin()
function as follows:
1 >>> bin(1)
2 '0b1'
3 >>> bin(10)
4 '0b1010'
5 >>> bin(100)
6 '0b1100100'
7 >>> bin(1000)
8 '0b1111101000'
82
CHAPTER 5 OPERATORS
= 8 + 0 + 2 + 0 = 1010 (5.2)
1 >>> bin(100)
2 '0b1100100'
3 >>> 100 << 1
4 200
5 >>> bin(200)
6 '0b11001000'
7 >>> 100>>1
8 50
9 >>> bin(50)
10 '0b110010'
11 >>> 100 << 2
12 400
13 >>> bin(400)
14 '0b110010000'
15 >>> 100 >> 2
16 25
17 >>> bin(25)
18 '0b11001'
83
CHAPTER 5 OPERATORS
The << shifts all bits of 100100 (11001002 ) to the left and fills the gap with
a new 0 and, thus, results in 110010002, which is equivalent to 20010. The >>
shifts all bits of 100100 (11001002) to the right and results in 1100102, which
is equivalent to 5010. Next, the bits are shifted two places.
The logical operators defined in Chapter 4 can be used here too.
Python’s boolean value True is equivalent to 1, and 0 is equivalent to
Python’s boolean value False. As a result, Tables 4-1, 4-2, 4-3, and 4-4 can
be redesigned as table
84
CHAPTER 5 OPERATORS
AND 0 1
0 0 0
1 0 1
OR 0 1
0 0 1
1 1 1
XOR 0 1
0 0 1
1 1 0
NOT 0 1
1 0
85
CHAPTER 5 OPERATORS
fast decode of the interrupt source. This is where bit operations come in
handy. Shift operators are used to shift the bits as per a formula, whereas
AND and OR operations are used to check the status of bits at a specific
location. The same concept is used to alter the system file permission.
In the Linux file system, each file has a number called its mode, which
indicates the permission about accessing the file. This integer can be
retrieved in a program to know the status of permissions for the file. For
example, if ((mode & 128) != 0) {<do this>} will check the mode by
checking if an appropriate bit is 0 in a 128-bit system. Bitwise operations
are also preferred for their speed of operation since they directly operate
on bits in the memory.
5.9. Summary
Operators play a very important role in computing as they provide the
backbone of defining pathways for computing. All mathematical functions
are expressed either by individual operators or by a combination of
them. For a programming language that caters to a variety of fields such
as science, engineering, business, and the arts, a lot of different kinds of
operators are needed. Python is now being applied in various dimensions
of life and maturing with a rich library of built-in as well as module-wise
operators.
86
CHAPTER 6
Arrays
6.1 Introduction
Most often during scientific computation, a series of numbers needs to be
operated upon together. The list data type stores a sequence of values.
All elements of list can be accessed by their index, but individual list
elements can belong to any data type. Hence, a new kind of object needs
to be defined, similar to list but that stores only numeric values. This data
type is called an array. This data type is not built in the Python interpreter,
but it is within the module numpy.
The numpy module carries a unique object class called array. It carries
member elements of only one data type. The concept of using arrays to
store numerals gave rise to a powerful idea of array-based computing.
The origins of this method can be traced back to matrix algebra.
A matrix is also a collection of numbers. Similar to matrices, arrays can
be multidimensional and can be operated on by operators defined the
same way as those for mathematical matrices. Using matrices, problems
involving a system of equations can be solved (which can even be
coupled to each other) in one instance. Using the method of indexing of
elements, particular elements can be accessed for operations. Using the
concept of slicing, array dimensions can be altered as per requirements.
Using operators acting on this object, mathematical formulations can
be implemented. In this chapter, we will discuss the use of arrays for
mathematical computations.
6.2 numpy
The numpy package contains various items that can be used for numerical
computation—hence, the name numerical Python. NumPy originated from
Numeric, which was originally created by Jim Hugunin with contributions
from several other developers. Travis Oliphant created NumPy in 2005
by incorporating features of the competing Numarray into Numeric, with
extensive modifications. numpy is released under an open source license.
This chapter’s code has been tested for version 1.12.1.
Just like any other Python module, numpy can be installed on Ubuntu
with a simple pip program:
Line 1 imports the whole module named numpy for our use. Line 2 uses
the function version, which further uses the function version to find the
installed version of numpy on the system. Users are encouraged to check
their version of Python.
It is also important to note that importing a module is necessary for
its usage, but once imported in a session, it doesn’t need to be imported
each time it is used. However, if the session is restarted, it must be freshly
imported. For this chapter, it can be imported once and then codes can
be written, but if a user shuts down the Python session and comes back to
start it again, it must be imported again.
88
CHAPTER 6 ARRAYS
6.3 ndarray
ndarray is the main object of numpy, which is homogeneous (containing
only one data type for all its member elements). The elements are created
using the array() function of numpy. This functions needs a list as input.
Elements are indexed by a tuple of positive integers:
1 >>> a = [1,2,3]
2 >>> a
3 [1, 2, 3]
4 >>> type(a)
5 <class 'list'>
6 >>> import numpy
7 >>> b = numpy.array([1,2,3])
8 >>> b
9 array([1, 2, 3])
10 >>> type(b)
11 <class 'numpy.ndarray'>
12 >>> b.dtype
13 dtype('int64')
14 >>> c = numpy.array([1.0, 2.0, 3.0])
15 >>> c
16 array([ 1., 2., 3.])
17 >>> c.dtype
18 dtype('float64')
This example shows how lists and arrays in numpy are created
differently. The numpy object array takes a list as input. The data type
of elements can be assigned by the Python interpreter at the time of
interpretation in a dynamic fashion. Alternatively, the data type can be
defined at the time of creation too using the second argument of the
array() function:
89
CHAPTER 6 ARRAYS
ndarray is also known by its alias array. Apart from knowing the data
type by using dtype, there are a variety of methods to get information
about various attributes of ndarray, as shown in Table 6-1.
Table 6-1 can be understood using the following Python code. We first
define a 3 array named a3 and then probe the property of this object using
the methods listed:
90
CHAPTER 6 ARRAYS
91
CHAPTER 6 ARRAYS
29 [8]])
30 >>>a3.reshape(9,1) is a3.reshape(1,9)
31 False
32 # result is false because both arrays have different shapes
6.4.1 zeros( )
To create an array where all elements are 0, we use the zeros() function:
6.4.2 ones( )
To create an array where all elements are 1, we use the ones() function:
93
CHAPTER 6 ARRAYS
6.4.3 ones_like( )
Taking its cue from an existing array, ones_like() creates a ones array of
similar shape and type:
6.4.4 empty( )
empty() returns an array of uninitialized (arbitrary) data of the given
shape, dtype, and order. Object arrays will be initialized to None. Unlike
zeros, it does not always set the array values to 0 value:
1 >>> numpy.empty((2,2))
2 array([[ 0., 0.],
3 [ 0., 0.]])
4 >>> numpy.empty((2,2),dtype=int)
94
CHAPTER 6 ARRAYS
5 array([[0, 0],
6 [0, 0]])
7 >>> numpy.empty((2,2),dtype=complex)
8 array([[ 3.10503618e+231 +3.10503618e+231j,
9 1.23516411e-322 +0.00000000e+000j],
10 [ 0.00000000e+000 +2.21170104e-314j,
11 2.21184108e-314 +2.25920578e-314j]])
12 >>> numpy.empty((2,2),dtype=str)
13 array([['', ''],
14 ['', '']],
15 dtype='<U1')
6.4.5 empty_like( )
Taking its cue from an existing array, empty_like() creates an empty array
of similar shape and type:
6.4.6 eye( )
Similar to an identity matrix, eye() returns a two-dimensional array where
diagonal elements are valued equal to 1. The function takes the second
argument as the index of the diagonal. 0 indicates the central diagonal.
A positive number means moving a designated number of steps in a
vertical upward direction. A negative number means moving a designated
number of steps in a vertical downward direction.
95
CHAPTER 6 ARRAYS
96
CHAPTER 6 ARRAYS
6.4.7 identity( )
The identity() function generates a two-dimensional identity array
with 1 as diagonal values. An equivalent matrix will be the one with
determinant as 1—hence, the name identity.
1 >>> numpy.identity(4)
2 array([[ 1., 0., 0., 0.],
3 [ 0., 1., 0., 0.],
4 [ 0., 0., 1., 0.],
5 [ 0., 0., 0., 1.]])
6 >>> numpy.identity(4,dtype=int)
7 array([[1, 0, 0, 0],
8 [0, 1, 0, 0],
9 [0, 0, 1, 0],
10 [0, 0, 0, 1]])
11 >>> numpy.identity(4,dtype=complex)
12 array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
13 [ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
14 [ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
15 [ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])
16 >>> numpy.identity(4,dtype=str)
17 array([['1', '', '', ''],
18 ['', '1', '', ''],
19 ['', '', '1', ''],
20 ['', '', '', '1']],
21 dtype='<U1')
97
CHAPTER 6 ARRAYS
6.4.8 full( )
full fills up particular data into all elemental positions:
1 >>>>>> numpy.full((3,2),10.5,dtype=int)
2 array([[10, 10],
3 [10, 10],
4 [10, 10]])
5 >>> numpy.full((3,2),10.5)
6 array([[ 10.5, 10.5],
7 [ 10.5, 10.5],
8 [ 10.5, 10.5]])
9 >>> numpy.full((3,2),10.5,dtype=complex)
10 array([[ 10.5+0.j, 10.5+0.j],
11 [ 10.5+0.j, 10.5+0.j],
12 [ 10.5+0.j, 10.5+0.j]])
13 >>> numpy.full((3,2),10.5+2j,dtype=complex)
14 array([[ 10.5+2.j, 10.5+2.j],
15 [ 10.5+2.j, 10.5+2.j],
16 [ 10.5+2.j, 10.5+2.j]])
17 >>> numpy.full((3,2),'a',dtype=str)
18 array([['a', 'a'],
19 ['a', 'a'],
20 ['a', 'a']],
21 dtype='<U1')
6.4.9 full_like( )
Just like empty_like and ones_like, full_like creates a new matrix
taking shape and data types from an existing array:
1 >>> numpy.full_like(a,5.0)
2 array([[ 5., 5., 5.],
98
CHAPTER 6 ARRAYS
1 >>> numpy.random.rand(4)
2 array([ 0.60855254, 0.81713983, 0.01249653, 0.55668541])
3 >>> numpy.random.rand(4,4)
4 array([[ 0.56770136, 0.45094011, 0.50791373, 0.29436197],
5 [ 0.664363 , 0.73385773, 0.55709437, 0.84207538],
6 [ 0.15050127, 0.56031549, 0.07850941, 0.0052116 ],
7 [ 0.54952592, 0.66695696, 0.07617147, 0.00457323]])
Note that the function rand() comes inside the subpackage random
within numpy. To get complete details of this wonderful package, we
encourage users to explore it using help(numpy.random) after issuing the
command import numpy.
The documentation describes a rich library of functions to create
random numbers as per choice. This makes numpy a good choice for
libraries used in simulation work. The choice of distribution depends
99
CHAPTER 6 ARRAYS
Random Integers
Random integers can be generated by using the numpy.random.random_
integers() and numpy.random.randint() functions. The latter needs the
first input as starting of the limit and the second as ending the limit for
random numbers.
The thrd argument can be a list describing the shape of the matrix:
100
CHAPTER 6 ARRAYS
101
CHAPTER 6 ARRAYS
Random Choice
Given one array, another array can be generated with its elements using
the numpy.random.choice() function:
102
CHAPTER 6 ARRAYS
6 [3, 3, 1, 9, 4, 4, 1, 2, 8, 6],
7 [5, 6, 8, 4, 3, 6, 8, 9, 3, 4],
8 [3, 7, 0, 4, 4, 2, 2, 9, 6, 8],
9 [1, 6, 4, 8, 8, 6, 9, 2, 3, 2],
10 [8, 4, 0, 2, 4, 0, 4, 5, 2, 9],
11 [5, 8, 2, 1, 4, 8, 8, 3, 2, 6],
12 [8, 4, 0, 1, 9, 1, 7, 0, 9, 9]])
13 >>> numpy.random.shuffle(a) # shuffle content of a
14 >>> a # contents of a have been shuffled indeed
15 array([[1, 6, 4, 8, 8, 6, 9, 2, 3, 2],
16 [1, 0, 5, 7, 6, 7, 6, 7, 3, 3],
17 [3, 3, 1, 9, 4, 4, 1, 2, 8, 6],
18 [3, 7, 0, 4, 4, 2, 2, 9, 6, 8],
19 [5, 6, 8, 4, 3, 6, 8, 9, 3, 4],
20 [0, 8, 3, 4, 8, 1, 9, 0, 6, 2],
21 [8, 4, 0, 2, 4, 0, 4, 5, 2, 9],
22 [8, 4, 0, 1, 9, 1, 7, 0, 9, 9],
23 [5, 7, 6, 7, 1, 1, 0, 9, 6, 8],
24 [5, 8, 2, 1, 4, 8, 8, 3, 2, 6]])
1 >>> a = numpy.random.randint(0,10,[10,10])
2 >>> a
3 array([[9, 6, 5, 0, 2, 5, 2, 6, 4, 5],
4 [6, 2, 0, 6, 9, 7, 5, 1, 6, 4],
5 [9, 3, 2, 6, 6, 7, 3, 1, 8, 8],
6 [9, 6, 4, 8, 2, 8, 7, 7, 4, 7],
7 [2, 6, 1, 1, 3, 0, 8, 5, 3, 5],
8 [8, 8, 7, 3, 4, 3, 5, 5, 0, 2],
9 [3, 5, 6, 8, 6, 6, 0, 7, 9, 2],
103
CHAPTER 6 ARRAYS
10 [8, 9, 6, 9, 4, 4, 5, 8, 1, 9],
11 [6, 0, 1, 8, 8, 7, 2, 7, 2, 1],
12 [1, 3, 4, 8, 9, 6, 4, 1, 9, 4]])
13 >>> numpy.random.permutation(a)
14 array([[8, 8, 7, 3, 4, 3, 5, 5, 0, 2],
15 [9, 6, 4, 8, 2, 8, 7, 7, 4, 7],
16 [3, 5, 6, 8, 6, 6, 0, 7, 9, 2],
17 [2, 6, 1, 1, 3, 0, 8, 5, 3, 5],
18 [9, 3, 2, 6, 6, 7, 3, 1, 8, 8],
19 [1, 3, 4, 8, 9, 6, 4, 1, 9, 4],
20 [6, 0, 1, 8, 8, 7, 2, 7, 2, 1],
21 [6, 2, 0, 6, 9, 7, 5, 1, 6, 4],
22 [8, 9, 6, 9, 4, 4, 5, 8, 1, 9],
23 [9, 6, 5, 0, 2, 5, 2, 6, 4, 5]])
Beta Distribution
The function numpy.random.beta() returns an array that follows beta
distribution, which is often encountered in Bayesian inference and order
statistics:
1 b -1
f ( x ;a ,b ) = x a -1 (1 - x ) (6.1)
B ( a ,b )
1
b -1
B (a ,b ) = òt a -1 (1 - t ) dt (6.2)
0
1 >>> a = numpy.random.beta(2,10,10)
2 >>> a
3 array([ 0.06604658, 0.21840079, 0.04368817, 0.08380568,
0.12769291,
4 0.06450275, 0.04227899, 0.04637705, 0.19960681, 0.24094982])
5 >>> a = numpy.random.beta(2,10,[3,3])
104
CHAPTER 6 ARRAYS
6 >>> a
7 array([[ 0.03500157, 0.15174638, 0.19104822],
8 [ 0.09989465, 0.0410233 , 0.10818969],
9 [ 0.05473703, 0.53414904, 0.09791452]])
Binomial Distribution
The function numpy.random.binomial(n,p,size=) returns an array that
follows binomial distribution [1]. Samples are drawn from a binomial
distribution with specified parameters, n trials, and p probability of success
where n is an integer >= 0 and p is in the interval [0, 1]. Let’s consider the
case where we have 50 trials and the probability of success is 80%:
1 >>> n, p = 50, .8
2 >>> a = numpy.random.binomial(n,p,10)
3 >>> a
4 array([41, 35, 42, 42, 34, 38, 38, 42, 40, 43])
5 >>> a = numpy.random.binomial(n,p,[3,3])
6 >>> a
7 array([[39, 36, 41],
8 [42, 38, 38],
9 [40, 43, 40]])
Normal Distribution
A normal (Gaussian) distribution of random numbers with a fixed mean
(a) and standard deviation (b) can be generated by using numpy.random.
random(a,b,size=):
105
CHAPTER 6 ARRAYS
Other Distributions
A lot of other distributions can also be used in the numpy.random
subpackage [2]. The choice of a particular distribution depends on the
simulation under study. Under a certain set of conditions, physical systems
follow a particular set of distributions.
106
CHAPTER 6 ARRAYS
7 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
8 >>> numpy.arange(1+2j,10+3j,0.1,dtype=complex) #
start=1+2j, stop=10+3j, step=0.1
9 array([ 1.0+2.j, 1.1+2.j, 1.2+2.j, 1.3+2.j, 1.4+2.j,
1.5+2.j,
10 1.6+2.j, 1.7+2.j, 1.8+2.j, 1.9+2.j])
107
CHAPTER 6 ARRAYS
6.5.4 meshgrid( )
The meshgrid is modeled after the MATLAB meshgrid command. To
understand the working of meshgrid, it’s best to use it once as follows:
1 >>> xx = numpy.linspace(1,3,3)
2 >>> xx
3 array([ 1., 2., 3.])
4 >>> yy = numpy.linspace(2,4,3)
5 >>> yy
6 array([ 2., 3., 4.])
7 >>> (a,b) = numpy.meshgrid(xx,yy)
108
CHAPTER 6 ARRAYS
8 >>> a
9 array([[ 1., 2., 3.],
10 [ 1., 2., 3.],
11 [ 1., 2., 3.]])
12 >>> b
13 array([[ 2., 2., 2.],
14 [ 3., 3., 3.],
15 [ 4., 4., 4.]])
mgrid[a:b , c:d]
constructs a grid where the x-axis has points from a to b and the y-axis has
points from c to d.
mgrid constructs a multidimensional meshgrid. The following example
demonstrates its use:
109
CHAPTER 6 ARRAYS
8 [6, 6, 6],
9 [7, 7, 7],
10 [8, 8, 8],
11 [9, 9, 9]])
12 >>> b
13 array([[2, 3, 4],
14 [2, 3, 4],
15 [2, 3, 4],
16 [2, 3, 4],
17 [2, 3, 4],
18 [2, 3, 4],
19 [2, 3, 4],
20 [2, 3, 4],
21 [2, 3, 4]])
22
23 >>> x, y = numpy.ogrid[0:5, 0:5]
24 >>> x
25 array([[0],
26 [1],
27 [2],
28 [3],
29 [4]])
30 >>> y
31 array([[0, 1, 2, 3, 4]])
110
CHAPTER 6 ARRAYS
6.6 tile( )
From a target array of a smaller size, a bigger array can be constructed
using the tile() function. tile() makes a copy of an existing array by the
defined number of times needed to make a new array:
1 >>> a = numpy.array([1,2,3])
2 >>> a
3 array([1, 2, 3])
4 >>> b = numpy.tile(a,3) # array a is repeated 3 times to
make a new array b
5 >>> b
6 array([1, 2, 3, 1, 2, 3, 1, 2, 3])
7 >>># Another example to do the same for two dimesnional
array
8 >>> a1 = numpy.eye(4)
9 >>> a1
10 array([[ 1., 0., 0., 0.],
11 [ 0., 1., 0., 0.],
12 [ 0., 0., 1., 0.],
13 [ 0., 0., 0., 1.]])
14 >>> a2=numpy.tile(a1,2) # repeat a1 in first dimesnion only
i.e row-wise
15 >>> a2
16 array([[ 1., 0., 0., 0., 1., 0., 0., 0.],
17 [ 0., 1., 0., 0., 0., 1., 0., 0.],
18 [ 0., 0., 1., 0., 0., 0., 1., 0.],
19 [ 0., 0., 0., 1., 0., 0., 0., 1.]])
20 >>> a2 = numpy.tile(a1,(2,2)) # repeat a1 in both
dimesnions 2 times
21 >>> a2
22 array([[ 1., 0., 0., 0., 1., 0., 0., 0.],
111
CHAPTER 6 ARRAYS
6.7 Broadcasting
Basic operations on numpy arrays are elementwise. This means that the
dimensions of the arrays should be compatible for the desired operation.
For example, 2 arrays and 2 arrays would be incompatible as the first array
has one fewer column than the second one.
1 >>>a = numpy.eye(4)
2 >>>b = numpy.array([1,2,3,4])
3 >>>c = a + b
4 >>>c
5
6 array([[ 2., 2., 3., 4.],
7 [ 1., 3., 3., 4.],
8 [ 1., 2., 4., 4.],
9 [ 1., 2., 3., 5.]])
10
11 >>>a.shape
12 (4L, 4L)
13
14 >>>b.shape
15 (4L,)
16
112
CHAPTER 6 ARRAYS
17 >>>c.shape
18 (4L, 4L)
19
20 # bradcasting enables array a ( 4 X 4) to be added to b (4
X 1) to produce an array c (4 X 4)
21
22 # Another example
23 >>>a = numpy.eye(4)
24 >>>a
25
26 array([[ 1., 0., 0., 0.],
27 [ 0., 1., 0., 0.],
28 [ 0., 0., 1., 0.],
29 [ 0., 0., 0., 1.]])
30
31 >>>b = numpy.array([10, 10, 10, 10])
32 >>>c = a + b
33 >>>c
34
35 array([[ 11., 10., 10., 10.],
36 [ 10., 11., 10., 10.],
37 [ 10., 10., 11., 10.],
38 [ 10., 10., 10., 11.]])
39
40 # A 4 X 4 matrix can be operated with a 4 X 1 matrix by
making the 'invisible' elemets zero.
113
CHAPTER 6 ARRAYS
6.9 Indexing
The elements of an array or list start with 0 in Python; the first element is
indexed 0. All elements can be accessed using their indexes:
114
CHAPTER 6 ARRAYS
These examples make it clear that arrays are similar to lists and follow
the same rules of indexing. Multidimensional arrays also follow the same
pattern of indexing. For two-dimensional arrays, the first number indicates
the row and the second number indicates the columns:
115
CHAPTER 6 ARRAYS
6 1
7 >>>a1[1,1] # chooisng an element whose row is indexed 1 and
clolumn is indexed 1 i.e. second row and second coloumn
8 2
9 >>>a1[1] # chooisng row with index 1 i.e second row
10 array([3, 2, 1])
6.10 Slicing
Among the first operations to be applied on arrays is slicing. Slicing
employs the operator :, which is used to separate the data on the row:
116
CHAPTER 6 ARRAYS
5 array([0, 1, 2, 3, 4])
6 >>>a1[:5] # [:5] selecets 'from' starting 'untill' index 5
i.e. excluding index 5
7 array([0, 1, 2, 3, 4])
8 >>>a1[2:5] # [2:5] selecets 'from' index 2 'untill' index 5
i.e. excluding index 5
9 array([2, 3, 4])
10 >>>a1[2:-2] # [2:-2] selecets 'from' index 2 'untill' index -2
(counting from right starts from -1) i.e. exclusing index -2
11 array([2, 3, 4, 5, 6, 7])
12 >>>a1[2:] # [2:] selecets 'from' index 2 'untill' last
index
13 array([2, 3, 4, 5, 6, 7, 8, 9])
14 >>>a1[0:5:2] # [start:stop:step] =[0:5:2] hence it takes a
tep of 2 while choosing indices from 0 to 5
15 array([0, 2, 4])
117
CHAPTER 6 ARRAYS
10 array([[1, 2],
11 [5, 6]])
12 >>>a1[0:2,0:4] # First slice indicates to collect only
first two elements by second slice indicates to collect
first four elements, hence using broadcasting the result is
implemented
13 array([[1, 2, 3, 4],
14 [5, 6, 7, 8]])
15 >>>a1[1:2,-1:] # because second slice indicates to collect
the last element
16 array([[9]])
1 >>>a = numpy.arange(10)
2 >>>a
3 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
4 >>>b = a[2:5]
5 >>>b
6 array([2, 3, 4])
7 >>>numpy.may_share_memory(a,b) # array 'a' and 'b' share
same memory space
8 True
118
CHAPTER 6 ARRAYS
119
CHAPTER 6 ARRAYS
6.12 Masking
Arrays can be indexed using the method of masking. Masking is a way to
define the indexes as a separate object and then generate a new array from
the original array using the mask as a rule. There are two ways that arrays
can be masked: fancy indexing and indexing using boolean values. It is
important to note that masking methods generate copies instead of views.
The two methods are discussed in the following subsections.
120
CHAPTER 6 ARRAYS
1 >>>a = numpy.arange(100).reshape(10,10) # a is a 10 X 10
matrix of first hundred numbers. Our aim is to make an
array of even numbers and make a 5 X 10 matrix
2 >>> a
3 array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
4 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
5 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
6 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
7 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
8 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
9 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
10 [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
11 [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
12 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
13 >>>b = (a % 2 ==0) # b now stores a matrix of boolean
values where the value is 'True' when the element of a is
divisible by two and value is 'False' when elemnet of a is
not divisible by two.
121
CHAPTER 6 ARRAYS
14 >>>a[b].reshape(5,10)
15 array([[ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
16 [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
17 [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
18 [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
19 [80, 82, 84, 86, 88, 90, 92, 94, 96, 98]])
122
CHAPTER 6 ARRAYS
11 >>>b
12 matrix([[0, 1, 2, 3, 4],
13 [5, 6, 7, 8, 9]])
1 >>>a_array = numpy.arange(12).reshape(3,4)
2 >>>a_array # 'a_array' stores a 3 X 4 array of numbers
3 array([[ 0, 1, 2, 3],
4 [ 4, 5, 6, 7],
5 [ 8, 9, 10, 11]])
6 >>>a_array_1 = a_array.copy # 'a_array_1' is a copy of
'a_array'
7 >>>sum_array = a_array + a_array # sum of two arrays
produces a new array where elementwise operation (addition
here) is performed
8 >>>sum_array
9 array([[ 0, 2, 4, 6],
10 [ 8, 10, 12, 14],
11 [16, 18, 20, 22]])
12 >>>scalar_product = 3 * a_array # scalar product of array
with a number is simply elementwise multiplication
13 >>>scalar_product
14 array([[ 0, 3, 6, 9],
15 [12, 15, 18, 21],
16 [24, 27, 30, 33]])
17 >>>a_matrix = numpy.matrix (a_array) # A matrix 'a_matrix'
is created using an array 'a_array'
18 >>>a_matrix
19 matrix([[ 0, 1, 2, 3],
123
CHAPTER 6 ARRAYS
20 [ 4, 5, 6, 7],
21 [ 8, 9, 10, 11]])
22 >>>sum_matrix = a_matrix + a_matrix
23 >>>sum_matrix
24 matrix([[ 0, 2, 4, 6],
25 [ 8, 10, 12, 14],
26 [16, 18, 20, 22]])
27 >>>scalar_mul_matrix = 3 * a
28 >>>scalar_mul_matrix = 3 * a_matrix
29 >>>scalar_mul_matrix
30 matrix([[ 0, 3, 6, 9],
31 [12, 15, 18, 21],
32 [24, 27, 30, 33]])
33 >>># Checking for transpose
34 >>>a_array_T = a_array.T # Transpose of array i.e rows and
copy are exchanged
35 >>>a_array_T
36 array([[ 0, 4, 8],
37 [ 1, 5, 9],
38 [ 2, 6, 10],
39 [ 3, 7, 11]])
40 >>>a_matrix_T = a_matrix.T # Transpose of matrix object
41 >>>a_matrix_T
42 matrix([[ 0, 4, 8],
43 [ 1, 5, 9],
44 [ 2, 6, 10],
45 [ 3, 7, 11]])
46 >>># checking for dot product of arays and matrices
47 >>>dot_array = numpy.dot(a_array, a_array_T)
48 >>>dot_array
49 array([[ 14, 38, 62],
124
CHAPTER 6 ARRAYS
Until now, the matrix has behaved exactly the same as an array. A
common question that arises in the minds of programmers is that if you
had an array object, what was the need of matrix ?
The answer is quite complex. While array serves most of the general
purposes for matrix algebra, matrix is written to facilitate linear algebra
functionalities. Linear algebra is performed using a submodule of numpy
accessed as numpy.linalg. Issuing the command help(numpy.linalg)
gives an idea about the purpose of this module. Following are some of the
useful functions from the matrix algebra point of view:
125
CHAPTER 6 ARRAYS
6.14.1 sum
sum() calculates the sum of all elements in the array if it is one-dimensional
or else it calculates the sum of elements of a column:
126
CHAPTER 6 ARRAYS
1 >>>a = numpy.arange(10).reshape(2,5)
2 >>>a
3 array([[0, 1, 2, 3, 4],
4 [5, 6, 7, 8, 9]])
5 >>>a.min()
6 0
7 >>>a.max()
8 9
9 >>>a.max(axis=0) # maximum in each coloumn
10 array([5, 6, 7, 8, 9])
11 >>>a.max(axis=1) # maximum in each row
12 array([4, 9])
1 >>>a = numpy.arange(10).reshape(2,5)
2 >>>a
3 array([[0, 1, 2, 3, 4],
4 [5, 6, 7, 8, 9]])
5 >>>numpy.mean(a) # mean of all values
6 4.5
7 >>>numpy.median(a) # median of ala value
8 4.5
127
CHAPTER 6 ARRAYS
6.14.4 sort( )
sort() sorts the array values from maximum to minimum:
1 >>> a = numpy.random.rand(3,4)
2 >>> a
3 array([[ 0.51389165, 0.65372872, 0.22264919, 0.41722141],
4 [ 0.19754059, 0.78218154, 0.0830597 , 0.44351731],
5 [ 0.54915984, 0.49219332, 0.24111783, 0.5021453 ]])
6 >>> numpy.sort(a)
7 array([[ 0.22264919, 0.41722141, 0.51389165, 0.65372872],
8 [ 0.0830597 , 0.19754059, 0.44351731, 0.78218154],
9 [ 0.24111783, 0.49219332, 0.5021453 , 0.54915984]])
10 >>> numpy.sort(a, axis=1) # sorting along columns
11 array([[ 0.22264919, 0.41722141, 0.51389165, 0.65372872],
12 [ 0.0830597 , 0.19754059, 0.44351731, 0.78218154],
13 [ 0.24111783, 0.49219332, 0.5021453 , 0.54915984]])
14 >>> numpy.sort(a, axis=0) # sorting along rows
15 array([[ 0.19754059, 0.49219332, 0.0830597 , 0.41722141],
16 [ 0.51389165, 0.65372872, 0.22264919, 0.44351731],
17 [ 0.54915984, 0.78218154, 0.24111783, 0.5021453 ]])
128
CHAPTER 6 ARRAYS
‘quicksort’ 1 O(n2) 0 no
1 >>> a = numpy.random.rand(10)
2 >>> a
3 array([ 0.15342238, 0.90475845, 0.90006375, 0.68768342,
0.14153903,
4 0.07962712, 0.59819738, 0.76087737, 0.97013725, 0.1560855 ])
5 >>> numpy.around(a)
6 array([ 0., 1., 1., 1., 0., 0., 1., 1., 1., 0.])
7 >>> numpy.around(a).astype(int)
8 array([0, 1, 1, 1, 0, 0, 1, 1, 1, 0])
129
CHAPTER 6 ARRAYS
6.16 Summary
Array-based computing is used as a primary force to solve equations and
systems of equations. Using slicing and indexing operations, it provides
powerful tools to manipulate data using a program. Since this book is an
interactive text on Python, discussion about all functions for indexing and
slicing is out of its scope.
130
CHAPTER 6 ARRAYS
6.17 Bibliography
[1] https://en.wikipedia.org/wiki/Binomial_
distribution.
[2] https://docs.scipy.org/doc/numpy-1.13.0/
reference/routines.random.html.
[3] http://docs.scipy.org/doc/numpy/reference/
generated/numpy.matrix.html.
[4] http://docs.scipy.org/doc/numpy/reference/
generated/numpy.sort.html.
131
CHAPTER 7
Plotting
7.1 Introduction
Plotting data is one of the most essential parts of numerical computation.
In pre-processing, during computation, and in post-processing, the ability
to plot data on different kinds of graphs is essential. Visualization of data in
a convenient format allows for better understanding of the process. Visual
clues generate a lot of information about the process that generated that
particular data. You can easily look for errors and derive simple as well as
complex interpretations. A good programming language must incorporate
facilities to plot data easily. Plotting two-dimensional (2-D) and three-
dimensional (3-D) graphs is vital for creating a good visualization product.
Python users have a number of choices in this regard.
In this chapter, we will discuss some of the choices. Essential
requirements while choosing a plotting library depends on requirements
of the data, such as the following:
The plotting library used for this chapter is called matplotlib. Just like
any other module, it they can be installed using pip on an Ubuntu system.
For Windows and Mac OS X users who use Anaconda IDE, this library is
pre-installed in the system.
7.2 matplotlib
John Hunter, the creator of matplotlib [1], rightly stated that “matplotlib
tries to make easy things easy and hard things possible [2].”
In some cases, with just one line of code, you can generate a high-
uality, publication-ready graphics visualization of the problem at hand.
Before Python, gnuplot was used to plot the data passed by a Python
script. With matplotlib available, this action has become very flexible.
matplotlib was modeled after the graphic capabilities of MATLAB, which
came as a boon for programmers who were already well versed with
MATLAB. Some of the major advantages of using matplotlib over other
plotting libraries are as follows:
134
CHAPTER 7 PLOTTING
is that it has a variety of plotting styles such as line, scatter, and bar charts
as well as histograms and many more. It can also be used interactively with
IPython. numpy is necessary for working with matplotlib. Hence, it must
be installed on the system before you can work with matplotlib.
matplotlib depends on a certain set of programs for proper
executions. These dependencies must be first installed [3]. This installation
is automatically done when pip is used, but users who wish to build it from
source must perform the same. This book is intended for beginners, so this
topic is not illustrated here.
135
CHAPTER 7 PLOTTING
136
CHAPTER 7 PLOTTING
The result can be seen in Figure 7-1. A plot needs two axes, which
are usually termed as the x-axis and y-axis. When the plot() command
is supplied with a single list or array, it assumes it to be the values for
the y-axis and automatically generates corresponding x values, taking its
cue from the length of list. We had 10 numbers. Consequently, the x-axis
had 10 numbers from 0 to 9. plot() can take both axes as input vectors
to produce a plot as shown in the code in Listing 7-2. This code uses the
pylab library instead of pyplot.
137
CHAPTER 7 PLOTTING
The result can be seen in Figure 7-2. A very basic plot could be plotted
by just a few lines of code where you first import relevant libraries (line
1 and line 2), then define the x- and y-axes, and finally use the plot
command, which gives the parameters for the x- and y-axes. These
commands can be issued one-by-one at the Python command prompt, or
they can be saved as a Python file. (Use a text editor, write the code, and
save with sqPlot1.py.)
The axes are defined as a numpy array. They can be generated by all the
methods available including creating them by hand, using a formula (like
in code sqPlot1.py—array named y is generated by elementwise squaring
of array x), using a data file, taking data live from a remote/local server
using the Internet or LAN, and so on. Subsequent chapters will deal with
file input/output facilities. In this chapter, only an array generated by self
or using formulas will be used.
138
CHAPTER 7 PLOTTING
1 import numpy as np
2 from matplotlib import pylab as pl
3 x = np.linspace(0,100)
4 y1 = x ** 2 # y is square of x
5 y2 = x ** 2.2 # y is x raised to power 2.2
6 pl.plot(x,y1)
7 pl.plot(x,y2)
8 pl.show()
139
CHAPTER 7 PLOTTING
Figure 7-3. Plotting more than one graph on the same axes
141
CHAPTER 7 PLOTTING
. Point
, Pixel
o Circle
v Triangle down
< Triangle left
> Triangle right
1 Tripod down
2 Tripod up
3 Tripod left
4 Tripod right
s Square
p Pentagon
∗ Star
h Hexagon
H Rotated hexagon
+ Plus
x Cross
D Diamond
d Thin diamond
- Horizontal line
142
CHAPTER 7 PLOTTING
- Solid line
– Dashed line
-. Dash dot line
: Dotted line
plot(range(10), '--g+')
b Blue
c Cyan
g Green
k Black
m Magenta
r Red
w White
y Yellow
143
CHAPTER 7 PLOTTING
In addition to using the predefined symbols for colors, you can also use
a hexadecimal string such as #FF00FF or a RGBA tuple like (1,0,1,1). You
can set grayscale intensity as a string like '0.6'.
grid(True)
A variety of options [4] are presented for 2-D line styles for setting
the line properties for a 2-D plot() functions. Code sqPlot3.py shows a
plotting of a formatted figure using a variety of formatter arguments, as
shown in Listing 7-4 and Figure 7-4.
7
8 # Create a new subplot from a grid of 1x1
9 pl.subplot(1, 1, 1)
10
11 # We wish to plot sin(x) and sin(2x)
12
13 # first we define x- axis in terms of pi units
14
15 X = np.linspace(-np.pi * 2, np.pi *2, 10e4, endpoint=True)
16
17 ''' x-axis is defined from -2pi to 2pi with 10000 points
18 where last point is also included'''
19
20 S, S2 = np.sin(X), np.sin(2*X)
21
22 # Plot sin(x) with a blue continuous line of width 1
(pixels)
23 # labelled as sin(x)
24 pl.plot(X, S, color="blue", linewidth=1.0, linestyle="-",
label = "$sin(x)$")
25
26 # Plot sine(2x) with a red continuous line of width 1
(pixels)
27 # labelled as sin(2x)
28 pl.plot(X, S2, color="red", linewidth=1.0, linestyle="-",
label = "$sin(2x)$")
29
30 # Set x limits from -2pi to 2.5*pi
31 pl.xlim(-2* np.pi, 2.5* np.pi)
32
33 # Set x ticks
34 pl.xticks(np.linspace(-2.5 * np.pi, 2.5 * np.pi, 9,
endpoint =True))
145
CHAPTER 7 PLOTTING
35
36 # Set y limits from 1.2 to -1.2
37 pl.ylim(-1.2, 1.2)
38
39 # Set y ticks
40 pl.yticks(np.linspace(-1, 1, 5, endpoint=True))
41
42 # Set the tile as 'Sine waves'
43 pl.title('$sin(x)$ and $sin(2x)$ waves')
44
45 # Setting label on x-axis and y-axis
46
47 pl.ylabel('$sin(x)$ and $sin(2x)$')
48 pl.xlabel('$x$')
49
50 # Setting the grid to be ON
51 pl.grid(True)
52
53 # To show a legend at one corner for differentiating two
curves
54 pl.legend()
55
56 # Show result on screen
57 pl.show()
146
CHAPTER 7 PLOTTING
7.5 Histograms
Histograms use vertical bars to plot events occurring with a particular
range of frequency (called bins). They can be simply plotted using the
hist() function, as shown in Listing 7-5.
147
CHAPTER 7 PLOTTING
1 import matplotlib.pyplot as pt
2 import numpy as np
3
4 a = np.random.rand(50)
5 pt.hist(a)
6 pt.show()
The umber of bins can be set to a number along with input variable, as
shown in Listing 7-6.
148
CHAPTER 7 PLOTTING
1 import matplotlib.pyplot as pt
2 import numpy as np
3
4 a = np.random.rand(50)
5 pt.hist(a,25) # setting number of bins to 25
6 pt.show()
149
CHAPTER 7 PLOTTING
1 import matplotlib.pyplot as pl
2 import numpy as np
3 x = np.array([1,2,3,4,5,6,7,8,9,0])
4 y = np.array([1,4,2,3,4,5,7,6,8,7])
5 pl.bar(x, y)
6 pl.title('Vertical Bar chart')
7 pl.xlabel('$x$')
8 pl.ylabel('$y$')
9 pl.show()
Bar charts and histograms look very similar. The difference lies in
the way you define them. Whereas bar() requires both x-axis and y-axis
arguments, hist() requires only an y-axis argument. barh() function plots
horizontal bars. (See Listing 7-8.)
150
CHAPTER 7 PLOTTING
1 import matplotlib.pyplot as pl
2 import numpy as np
3 x = np.array([1,2,3,4,5,6,7,8,9,0])
4 y = np.array([1,4,2,3,4,5,7,6,8,7])
5 pl.barh(x, y)
6 pl.title('Horizontal Bar chart')
7 pl.xlabel('$x$')
8 pl.ylabel('$y$')
9 pl.show()
151
CHAPTER 7 PLOTTING
1 import matplotlib.pyplot as pl
2 import numpy as np
3 x = np.arange(0, 4, 0.2) # generated data point from 0 to 4
with step of 0.2
4 y = x*2 # y = e^(-x)
5 err = np.array([0,.1,.1,.2,.1,.5,.9,.2,.9,.2,.2,.2,.3,.2,
.3,.1,.2,.2,.3,.4])
6 pl.errorbar(x, y, yerr=err, ecolor='r')
7 pl.title('Error bar chart with symmetrical error')
8 pl.xlabel('$x$')
9 pl.ylabel('$y$')
10 pl.show()
152
CHAPTER 7 PLOTTING
ecolor sets the color for error bars. Just as you can the value for yerr
keyword, you can also set xerr to produce error bars on the x-axis.
In Listing 7-10, error bars are symmetrical—that is, positive and
negative errors are equal. For plotting asymmetrical error bars, errorbar()
would incorporate two arrays for error definition.
1 import matplotlib.pyplot as pl
2 import numpy as np
3 x = np.arange(0, 4, 0.2) # generated data point from 0 to 4
with step of 0.2
4 y = x*2 # y = e^(-x)
5 err_positive = np.array([0.5,.1,.1,.2,.1,.5,.9,.2,.9,.2,
.2,.2,.3,.2,.3,.1,.2,.2,.3,.4])
6 err_negative = np.array([0.2,.4,.3,.1,.4,.3,.1,.9,
.1,.3,.5,.0,.5,.1,.2,.6,.3,.4,.1,.1])
153
CHAPTER 7 PLOTTING
154
CHAPTER 7 PLOTTING
between particular data ranges. This is one of the key actions required by
regression analysis. (See Listing 7-11.)
1 import matplotlib.pyplot as pl
2 import numpy as np
3 x = np.random.rand(1000)
4 y = np.random.rand(1000)
5 pl.scatter(x,y)
6 pl.title('Scatter Chart')
7 pl.xlabel('$x$')
8 pl.ylabel('$y$')
9 pl.show()
155
CHAPTER 7 PLOTTING
1 import matplotlib.pyplot as pl
2 import numpy as np
3 x = np.array([1,2,3,4,5,6,7,8,9,0])
4 label = ['a','b','c','d','e','f','g','h','i','j']
5 explode = [0.2, 0.1, 0.5, 0, 0, 0.3, 0.3, 0.2, 0.1,0]
6 pl.pie(x, labels=label, explode = explode, shadow=True,
autopct ='%2.2f%%')
7 pl.title('Pie Chart')
8 pl.show()
156
CHAPTER 7 PLOTTING
When the explode label is not defined, you get an unexploded pie
chart. autopct sets the percentage of weight for a particular weight, which
can be set by format specifier. %2.2f%% sets the display of percentage
weights up to two decimal places with two significant digits. shadow
provides a shadow below the wedge so that it looks like a real pie!
157
CHAPTER 7 PLOTTING
1 import matplotlib.pyplot as pl
2 import numpy as np
3
4 r = np.arange(0, 10.0, 0.1)
5 theta = 2* np.pi * r
6
7 pl.polar(theta, r, color ='g')
8 pl.show()
158
CHAPTER 7 PLOTTING
Listing 7-14.
1 import matplotlib.pyplot as pl
2 import numpy as np
3 x = np.arange(0, 2*np.pi, .01)
4 y = np.sin(x)
5 pl.plot(x, y, color = 'r');
159
CHAPTER 7 PLOTTING
160
CHAPTER 7 PLOTTING
As seen in Listing 7-14, the text, arrow, and annotations can be placed
at appropriate places by defining coordinate axis points for them. A
convenient method of identifying appropriate coordinates is to roll over
the mouse on the body of the plot and look for the down-left corner of the
figure where present mouse coordinates are shown. help(matplotlib.
pyplot.annotate) gives useful inputs to use this function.
7.12 Subplots
Multiple plots can be plotted using the subplot option where different plots
are considered to be a matrix of graphs. Just like a regular matrix, elements
are identified by index. As seen in Listing 7-15, subplots are located using
indices like (222), which essentially means that the matrix is a 2 × 2 and
one is accessing the second position to place the scatter() function-
based plot. Similarly (221) uses a plot() function at the first position, (223)
at the third position plots a histogram using the hist() function, and (224)
is the fourth plot using barh(), giving a horizontal bar graph.
1 import matplotlib.pyplot as pl
2 import numpy as np
3
4 x = np.arange(10)
5 y1 = np.random.rand(10)
6 y2 = np.random.rand(10)
7
8 fig = pl.figure()
9
10
11 ax1 = fig.add_subplot(221)
12 ax1.plot(x,y1)
161
CHAPTER 7 PLOTTING
13
14 ax2 = fig.add_subplot(222)
15 ax2.scatter(x,y2)
16
17 ax3 = fig.add_subplot(223)
18 ax3.hist(y1)
19
20 ax4 = fig.add_subplot(224)
21 ax4.barh(x,y2)
22
23 pl.show()
162
CHAPTER 7 PLOTTING
1 import matplotlib.pyplot as pt
2 import numpy as np
3 pt.plot (np.arange (10))
4 pt.savefig ('plot1.png')
163
CHAPTER 7 PLOTTING
It is important to know the size of the file and the resolution of the
figure for the purpose of publication at both offline/print and online
media. When none of the arguments for setting the resolution of the figure
and size of the file are set within the program, default values are used.
These default values can be known using the following code:
1 >>>import matplotlib as ml
2 >>>ml.rcParams['figure.figsize']
3 [8.0, 6.0]
4 # Default figure size is 8 X 6 inches
5 >>>ml.rcParams['savefig.dpi']
6 100.0
7 # Default figure resolution is 100 dpi
Since a 8 × 6 inch figure is created with 100 dpi (dots/pixels per inch), a
800 × 600 pixels image is saved using savefig() by default. When this file
is directed toward a computer graphic terminal for displaying, length units
are ignored and pixels are displayed. If the file is directed toward a printing
media like a printer or plotter, length parameters and DPI determine figure
size and resolution.
164
CHAPTER 7 PLOTTING
2 (agg) rendering
1 >>>import matplotlib
3 output by default
165
CHAPTER 7 PLOTTING
1 $ ipython −pylab
This command produces the graphs inline, that is, within the body
of the code in between the command lines where the plot is called.
Otherwise, the plots pop out in a separate window. Inline mode is
useful while designing teaching materials. However, before sharing with
concerned persons, it should be ensured that encoded backends and
dependencies are installed on the user’s computer.
166
CHAPTER 7 PLOTTING
168
CHAPTER 7 PLOTTING
169
CHAPTER 7 PLOTTING
170
CHAPTER 7 PLOTTING
171
CHAPTER 7 PLOTTING
172
CHAPTER 7 PLOTTING
It is worth noting that two different axes instances, namely ax1 and
ax2, are superimposed on each other where data from y1 being allotted
to axes instance ax1 and data from y2 being allotted to axes instance
ax2. This also illustrates the power of defining a plot in object mode. The
corresponding plot is given in Figure 7-19.
173
CHAPTER 7 PLOTTING
Hence, contour lines are also called level lines or isolines. The term iso
is attached to data points having constant value and the regions of these
data points are separated by contours.
For a contour plot, you need x-, y- and z-axes where the z-axis defines
the height. The data with the same height is clubbed together within
isolines. (See Listing 7-20.)
174
CHAPTER 7 PLOTTING
24 lx2 = ax2.set_xlabel("x")
25 ly2 = ax2.set_ylabel("y")
26
27 plt.show()
28
29 # plotting filled contour
175
CHAPTER 7 PLOTTING
176
CHAPTER 7 PLOTTING
17 ax.set_ylabel('$y = sin(x)$')
18 ax.set_zlabel('$z = cos(x)$')
19 plt.show()
Scatter plots are plotted in 3-D in a similar way to line plots. This is
illustrated in the Python script Listing 7-22 and the corresponding graph is
shown in Figure 7-21.
1 import numpy as np
2 from mpl_toolkits.mplot3d import Axes3D
3 import matplotlib.pyplot as plt
4
5 fig = plt.figure()
6 ax = fig.add_subplot(111, projection='3d')
7
8 x = np.linspace(-5*(np.pi), 5*(np.pi),200)
9 y =np.sin(x)
10 z =np.cos(x)
11
12 ax.scatter(x, y, z, marker='*')
13
14 ax.set_xlabel('$x$')
15 ax.set_ylabel('$y = sin(x)$')
16 ax.set_zlabel('$z = cos(x)$')
17 ax.set_title('Scatter plot in 3D')
18
19 plt.show()
178
CHAPTER 7 PLOTTING
z = x2 + y2
179
CHAPTER 7 PLOTTING
Surface plots are similar to wiremesh plots except for the fact that it’s
continuously filled up. Hence, instead of the wiremesh() function, you use
the surface() function. (See Listing 7-24.)
180
CHAPTER 7 PLOTTING
181
CHAPTER 7 PLOTTING
182
CHAPTER 7 PLOTTING
26
27
28
29 plt.show()
183
CHAPTER 7 PLOTTING
4
5 x = np.linspace(np.pi,-(np.pi),10)
6 y = np.linspace(np.pi,-(np.pi),10)
7 (X,Y) = np.meshgrid(x,y)
8 u = -15*X
9 v = 5*Y
10 q = plt.quiver(X,Y,u,v,angles='xy',scale=1000,color='b')
11 #p = plt.quiverkey(q,1,16.5,50,"50 m/s",coordinates='data',
color='r')
12 xl = plt.xlabel("x (km)")
13 yl = plt.ylabel("y (km)")
14 plt.show()
184
CHAPTER 7 PLOTTING
7.20.1 plotly
plotly is an online analytics and data-visualization tool. In addition
to Python, plotly can plot data used in Perl, Julia, Arduino, R, and
MATLAB. Weblink [5] gives a pretty good sense of the capabilities of
plotly. Essentially, plotly allows plotting and publishing graphs online
to encourage collaboration. Hence, you must be connected to the Internet
before working with the plotly library.
First, you need to make a user account at the plotly web site [5]. The
account will provide a username and API key, which needs to be used in
the program. Then, you can write a code either as one command at a time
on a Python terminal or as a Python script. (See Listing 7-27.)
1 import numpy as np
2 import plotly.plotly as py
3 from plotly.graph_objs import *
4 py.sign_in('username','APIkey')
5 data = Data([Scatter(x=np.arange(100),y=np.random.
randn(100), name='trace 0')])
6 fig = Figure(data=data)
7 plot_url = py.plot(fig)
185
CHAPTER 7 PLOTTING
You need to provide the username and API key in the script in Listing 7-27.
The script results in generating a scatter plot online at a workspace in the user
account. These graphs can be plotted quite interactively using the functions
provided by plotly. When data are steamed from a device connected to a live
sensor, live data is plotted in real time. This can further be embedded on a
web site.
7.21 Summary
In this chapter, we have discussed various plotting options available while
working with Python. The ease of plotting data is one of the most attractive
features of Python. Just a few lines of code provide visualization of the data
in a variety of ways. Visualization is the backbone of data presentation
and analysis since it makes understanding of the data clearer. In addition
to simple visualization, matplotlib provides rich features to decorate the
graph with useful information in a desired manner.
7.22 Bibliography
[1] J. D. Hunter, “Matplotlib: A 2d graphics
environment,” Computing In Science & Engineering,
vol. 9, no. 3, pp. 90–95, 2007.
[2] http://matplotlib.org/.
[3] https://matplotlib.org/users/installing.html.
[4] http://matplotlib.org/api/lines_api.
html#matplotlib.lines.Line2D.
[5] https://plot.ly/.
186
CHAPTER 8
188
Chapter 8 FunCtions and Loops
1 def greet():
2 '''
3 greet() just greets with the string
4 "Hello World!" each time it is called
5 '''
6 print("Hello world!")
7
8 greet()
1 >>>python fn−hello.py
2 >>>Hello World!
189
Chapter 8 FunCtions and Loops
1 def square(x):
2 '''
3 square() squares the input value
4 One must only used numeric data types
5 to avoid getting error
6 '''
7 return x*x
8
9 for i in range(10):
10 squared_i= square(i)
11 print(i, squared_i)
1 >>>0 0
2 1 1
3 2 4
4 3 9
5 4 16
6 5 25
190
Chapter 8 FunCtions and Loops
7 6 36
8 7 49
9 8 64
10 9 81
Here the function square is called inside a “for loop,” which increments
the value of the variable i from 1 to 10 (generated by the built-in function
range()). The for loop structure will be discussed in Section 8.6.
1 def sum(a,b):
2 '''
3 sum() takes two inputs and produces
4 a tuple of inputs and thier sum
5 '''
6 c = a+b
7 return a,b,c
8
9 results = sum(100,102)
10 print(results)
191
Chapter 8 FunCtions and Loops
8.4 Namespaces
When we call a function within a program, Python creates a namespace
to work within this function. The namespaces are containers that store
information about mapping names to objects. Since multiple functions
can be defined within a main program, multiple namespaces can exit at
the same time independently. They can contain the same variable names.
Hence, a hierarchy level must be defined for conflict resolution. This is
defined by scope rules.
192
Chapter 8 FunCtions and Loops
193
Chapter 8 FunCtions and Loops
194
Chapter 8 FunCtions and Loops
195
Chapter 8 FunCtions and Loops
a 2 + b2 = c 2
This can be accomplished using for loop as given in the Python code
pytha.py shown in Listing 8-6. In this Python code, the user inputs a
number denoting the maximum number for which this calculation will be
performed. This ensures that the calculation has a proper end condition
(without explicit definition).
196
Chapter 8 FunCtions and Loops
28 48 140 148
29 50 120 130
30 54 72 90
31 56 90 106
32 56 192 200
33 60 80 100
34 60 144 156
35 64 120 136
36 66 88 110
37 66 112 130
38 70 168 182
39 72 96 120
40 72 154 170
41 78 104 130
42 78 160 178
43 80 84 116
44 80 150 170
45 80 192 208
46 84 112 140
47 90 120 150
48 96 110 146
49 96 128 160
50 96 180 204
51 102 136 170
52 108 144 180
53 112 180 212
54 114 152 190
55 120 126 174
56 120 160 200
57 120 182 218
58 126 168 210
59 130 144 194
198
Chapter 8 FunCtions and Loops
As an exercise, you can write a few more lines of code to check if there
are any prime number triplets as Pythagorean numbers.
199
Chapter 8 FunCtions and Loops
7 if area == "I":
8 if total <= 500:
9 print("Shipping Costs INR 20.00")
10 elif total <= 1000:
11 print("Shipping Costs INR 100.00")
12 elif total <= 1500:
13 print("Shipping Costs INR 250.00")
14 else:
15 print("FREE")
16
17 if area == "O":
18 if total <= 500:
19 print("Shipping Costs INR 75.00")
20 elif total <= 1000:
21 print("Shipping Costs INR 200.00")
22 elif total <= 1500:
23 print("Shipping Costs INR 500.00")
24 else:
25 print("FREE")
200
Chapter 8 FunCtions and Loops
1 while expression:
2 statement(s)
202
Chapter 8 FunCtions and Loops
Note that the output time might be different for each execution
even on same the computer since time taken to process a line of code is
functional of the state of CPU at that particular moment of time.
203
Chapter 8 FunCtions and Loops
Since the condition always remains true, the program will never quit
displaying the value of i, which is 1. It will never print the last line of the
code. On a Linux machine, you need to press CTRL+C to interrupt the
executing and come back to the command line.
8.10 while-else
Within a while loop, the statements are executed if the condition produces
a boolean value True. Using an else statement within this structure allows
the user to route the flow of the program if the condition returns the
boolean value False, as shown in Listing 8-10.
204
Chapter 8 FunCtions and Loops
1 0
2 1
3 2
4 3
5 4
6 the value execeeds 5
8.11 Summary
Functions enable the modular structure of programs. Additionally,
controlling the flow of information as well as iterations has become the
very basis of computational work in most applications. These two actions
are performed by loops. Together, they make Python a powerful tool
for various applications. Having a modular structure makes it easier to
test and debug. Mastering the skill of writing functions and the skill of
choosing the proper loop structure has become key indicators for ranking
a programmer’s performance in solving problems using Python codes.
Hence, this chapter is very important for programmers.
205
CHAPTER 9
Object-Oriented
Programming
9.1 Introduction
The idea of defining objects is quite natural to humans since we deal
with objects in our day-to-day life. We understand an object as something
that has
9.3 Objects
In the Python world, everything is an object. But what is an object? An
object is an abstract concept to signify an entity on which computation
can be performed. Just like a physical object, a computer’s object has a
set of attributes and a related set of behaviors. A number, string, pictures,
videos, and files can be visualized as objects. Within numbers, you
can subcategorize objects into other objects such as integers, floating
point numbers, and boolean numbers, or their collection in an ordered
or unordered fashion. Within strings, you can have characters, words,
sentences, and so on. Within files, you can have text files, media files, data
files, script files, and so forth. Let’s explore some common Python objects:
1 >>>a=10.0
2 >>>help(a)
3 Help on float object :
4
5 class float(object)
6 | float(x) −> floating point number
7 |
208
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
209
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
1 >>> a=1
2 >>> dir(a)
3 ['__abs__', '__add__', '__and__', '__bool__', '__ceil__',
'__class__', '__delattr__', '__dir__', '__divmod__',
'__doc__', '__eq__', '__float__', '__floor__',
'__floordiv__', '__format__', '__ge__',
210
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
211
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
The following sections will explain the ways to define objects and their
usage. First, let’s understand that different types of data must be treated
differently in a computer for their mathematical nature and for defining
computational resource requirements intelligently.
9.4 Types
An object has an associated type. Type dictates the memory storage
requirements and what can be done computationally with an object.
For example, int and float are distinct types of an object in the sense
that int stores integers and float stores floating point numbers. While
float needs to store information about how many digits precede and
succeed the decimal point, int objects do not need to worry about the
same. Similarly, a complex number is stored in another type of object
(aptly named complex) since it needs to store two aspects of a complex
numbers: their real and imaginary parts. In this way, they must be stored
quite differently in computer memory and then used quite differently in
subsequent computations.
212
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
1 >>> a =1
2 >>> type(a)
3 <class 'int'>
4 >>> b=1.0
5 >>> type(b)
6 <class 'float'>
7 >>> c =2+3j
8 >>> type(c)
9 <class 'complex'>
10 >>> d = 'd'
11 >>> type(d)
12 <class 'str'>
13 >>> e = 'addition'
14 >>> type(e)
15 <class 'str'>
16 >>> f = [1,2,3]
17 >>> type(f)
18 <class 'list'>
19 >>> g = 1,2,3
20 >>> type(g)
21 <class 'tuple'>
22 >>> import numpy as np
23 >>> a=np.array([1,2,3])
24 >>> type(a)
25 <class 'numpy.ndarray'>
26 type(np.sin)
27 <class 'numpy.ufunc'>
213
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
1 >>> a1 = 10
2 >>> id(a1)
3 4469844832
4 >>> a2=a1
5 >>> id(a2)
6 4469844832
7 >>> a3=20
8 >>> id(a3)
9 4469845152
10 >>> a3=a2
11 >>> id(a2)
12 4469844832
13 >>> id(a3)
14 4469844832
214
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
15 >>> a1
16 10
17 >>> a2
18 10
19 >>> a3
20 10
215
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
First, we create a list object with value [1,2,3] whose reference value
is list1. Next, we create another reference value, list2, in addition to the
original reference value list1 referring to the original list object ([1,2,3]).
When the second item on the list is altered by line number 7, it is reflected
by both reference values since both of these point to the same object.
216
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
Hence, list2 seems a copy of list1, which follows its original master
diligently. Let’s investigate if this pattern holds when its members of lists
are lists themselves:
So, it seems that even if members of list objects are list objects
themselves, the copying activity works the same way when members were
other objects.
The following code shows what happens if we use list constructor:
217
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
8 >>> list2[1]=list([-1,0,1])
9 >>> list2
10 [[1, 2, 3], [-1, 0, 1], [1, 2, 3]]
11 >>> list3
12 [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
13 >>> id(list2)
14 4416356864
15 >>> id(list3)
16 4416356936
Note that the reference value list3 has different data because they
now point to two different objects (as seen by their memory id values).
Hence, a copy of the original list did not follow the master diligently under
list constructor. Thus, list3 is said to be a shallow copy of list2.
Sometimes, we may like to make a copy and keep it unchanged under
various transformations even if list constructors are used. For this
purpose, the module named copy provides two methods named
copy.copy() and copy.deepcopy(). As per Python documentation [8]:
• A shallow copy constructs a new compound object and
then (to the extent possible) inserts references into it
to the objects found in the original. This is performed
using the copy.copy() method of copy module.
1 >>>import copy
2 >>> a = [[1, 2, 3], [4, 5, 6]]
3 >>> b = list(a)
4 >>> a
5 [[1, 2, 3], [4, 5, 6]]
218
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
6 >>> b
7 [[1, 2, 3], [4, 5, 6]]
8 >>> a[0][1] = 10
9 >>> a
10 [[1, 10, 3], [4, 5, 6]]
11 >>> b # list b changes too => Not a deepcopy.
12 [[1, 10, 3], [4, 5, 6]]
1 >>> b = copy.deepcopy(a)
2 >>> a
3 [[1, 10, 3], [4, 5, 6]]
4 >>> b
5 [[1, 10, 3], [4, 5, 6]]
6 >>> a[0][1] = 9
7 >>> a
8 [[1, 9, 3], [4, 5, 6]]
9 >>> b # list b doesn't change => Deep Copy
10 [[1, 10, 3], [4, 5, 6]]
As you can see, it enables b to retain its value even when a is changed.
9.6 Class
Until now, we have just discussed predefined objects and scanning their
type and their memory id. Using special types of objects called class, we
can create other objects.
The concept of class is also derived from the natural world. Objects
in the real world are classified according to their attributes and behavior.
An object is merely an instance of its class. For example, men and women
are merely instances of the class homo sapiens. In a similar fashion, the
keyword class defines a class of objects for which various instances can
219
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
be defined. For example, a class for numbers can have instances like
integers, floating point numbers, complex numbers, rational numbers,
and irrational numbers. Once defined, all members of this class will
share certain attributes and behaviors common to numerals, but they
can be further subdivided based on their differences. All members of this
class will be quite different from a class of language having characters,
words, sentences, and paragraphs. Now an instance of number class as an
integer and an instance of language class as a character can be defined for
computing. These instances of their respective classes will have their own
attributes and methods (some of them shared with their class and some of
their own). This object orientation helps us break down a complex system
into small fundamental units for easier study.
Thus, a class defines the behaviors of a new kind of abstract entity,
whereas an object is just a particular instance of that object. Classes and
objects help to define actions of functions on data in a manageable way
that can be managed in a similar fashion irrespective of the nature of data
and functions. An interface describes the functionalities of an object,
whereas its actual implementation defines how these functionalities can
be performed. Classes have constructors (we have already discussed the
constructor list() in Section 9.5.2) that dictate the creation of an object
of a particular kind. Encapsulation and inheritance describe the hierarchal
structure of classes with their super-classes. These concepts will be further
elaborated in subsequent sections.
220
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
1 class Name_of_class:
2 '''Optional class documentation string'''
3 statements
Name_of_class. __doc__
221
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
Class methods are different from ordinary functions in just one way.
They are required to have an extra first name. This first name needs to be
added to the beginning of the parameter list. Users do not give a value for
this parameter when they call the method. It is provided by Python’s main
program, which is run by the Python interpreter by default. This particular
variable refers to the object itself. Thus, it is given the name self. Those
methods that do not take any arguments have at least the argument as
self. Listing 9-1 will make this concept clearer.
222
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
1 $python Ex-class.py
2 The type of object storing class calling is:
<class'__main__.first_program'>
3 Hello World!
4
5 Hello again!
6
7 Hello Everybody
8
9
10 This program has two methods: hi and hi_again
9.6.3 Constructor
All objects within a class are merely instances of the class. When this
instance is initiated, a special kind of functions is called. A constructor is
a function that is executed when an object is instantiated. Python always
names a constructor as __init()__ since it sets the initial state of the
object. It defines the initial state and the basic nature of this instance. It is
223
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
defined within class definition, but a user can omit this definition because
every class automatically creates a default constructor. It is generally used
to define the initial values of the instance variables, as shown in Listing 9-2.
224
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
25 print(type(book1))
26
27 book2 = library("Basic Python",150) # Second instance
of object "library"
28 print(type(book2))
29
30 book3 = library("Intermediate Python",200) # Third instanc
of object "library"
31 print(type(book3))
32
33 book4 = library("Advanced Python",300) # Four instance
of object "library"
34 print(type(book2))
35
36 # Accessing attributes
37
38 print("Details of first book:")
39 book1.displayBook()
40
41 print("Details of second book:")
42 book2.displayBook()
43
44 print("Details of third book:")
45 book3.displayBook()
46
47 print("Details of fourth book:")
48 book4.displayBook()
49
50 print("Total Number of books= %d" % library.bookCount)
51
52 # Probing the bult-in attributes
53
225
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
54 print("library.__doc__:", library.__doc__)
55 print("library.__name__:", library.__name__)
56 print("library.__module__:", library.__module__)
57 print("library.__bases__:", library.__bases__)
58 print("library.__dict__:", library.__dict__)
• __doc__
• __dict__
227
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
• __module__
• __doc__
• Constructor __init__
• __name__
• __module__
• __bases__
1 <class '__main__.library'>
2 <class '__main__.library'>
3 <class '__main__.library'>
4 <class '__main__.library'>
5 Details of first book:
6 Name: Introduction to python , Price: 100
7 Details of second book:
8 Name: Basic Python , Price: 150
228
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
9.7 Summary
In this chapter, we have illustrated how to define a new kind of object using
the class construct. Since Python considers everything as an object, it
is one of the favorite choices for scientific computation and simulation.
Because it is easy to learn, users can start serious scientific computing
very quickly. This fact makes it very popular among educators, students,
and researchers. The ability to make classes and create your own modules
enables developers to enrich the Python ecosystem on a daily basis.
Hence, it isn’t an overstatement to say that the object-oriented nature
of Python and its open source ecosystem have made it one of the most
popular programming languages.
229
CHAPTER 9 OBJECT-ORIENTED PROGRAMMING
9.8 Bibliography
[1] http://propella.sakura.ne.jp/earlyHistoryST/
EarlyHistoryST.html.
[2] http://web.cecs.pdx.edu/~harry/musings/
SmalltalkOverview.html.
[3] R. Jones, A. Hosking, and E. Moss, The garbage
collection handbook: The art of automatic memory
management. Chapman & Hall/CRC, 2011.
[5] https://docs.python.org/3/library/gc.html.
[6] http://www.digi.com/wiki/developer/index.
php/Python_Garbage_Collection.
[7] http://arctrix.com/nas/python/gc/.
[8] https://docs.python.org/2/library/copy.html.
230
CHAPTER 10
Numerical Computing
Formalism
10.1 Introduction
Numerical computation enables us to compute solutions for numerical
problems, provided we can frame them into a proper format. This requires
certain considerations. For example, if we digitize continuous functions,
we are going to introduce certain errors due to the sampling at a finite
frequency. Hence, a very accurate result would require a very fast sampling
rate. In cases when a large dataset needs to be computed, it becomes a
computationally intensive and time-consuming task. Also, users must
understand that the numerical solutions are an approximation, at best,
when compared to analytical solutions. The onus of finding their physical
meaning and significance lies on us. The art of discarding solutions that do
not have a meaning for a real-world scenario is something that a scientist/
engineer develops over the years. Furthermore, a computational device is
just as intelligent as its operator. The law of GIGO (garbage in, garbage out)
is followed very strictly in this domain.
In this chapter, we will consider some of the important steps in solving
a physical problem using numerical computation. Defining a problem
in proper terms is just the first step. Making the right model and then
using the right method to solve (solver) the problem distinguishes an
experienced scientist/engineer from a novice.
3 x + 4 y + 9z = 10
232
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
233
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
-x + 3y = 4 (10.1)
2 x - 4 y = -3 (10.2)
é -1 3 ù é x ù é 4 ù
ê 2 -4 ú + ê y ú = ê 3 ú
ë û ë û ë û
Now using matrix algebra, the values of variables x and y can be found
such that they satisfy the equations. These values are called the roots of
these equations. These roots are the point in 2-D space (because we had
two dependent variables) where the system will find stability for that
physical problem. In this way, we can predict the behavior of the system
without actually doing an experiment.
The mathematical concept of differentiation and integration becomes
very important when we work with a dynamic system. When the system
is constantly changing the values of dependent variables to produce a
scenario, it is important to know the rate of change of these variables.
When these variables are independent of each other, we use simple
derivatives to define their rate of change. When they are not independent
of each other, we use partial derivatives.
For example, Newton’s second law of motion says that rate of change of
velocity of an object is directly proportional to the force applied on it. We
can show this concept mathematically:
dy
Fa (10.3)
dx
234
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
dy
F =m´ (10.4)
dx
235
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
on the LINUX command line. Users are encouraged to check out the
following packages for scientific computation:
236
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
• Object-oriented programming
• Architecture independence
• Networking
• Security
237
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
• Formulating variables
238
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
reduction of time for prototyping a solution as most of the time for devising
a solution is spent in debugging. In addition to this fact, Python is devised
for simple, intuitive, and minimalistic syntax, which further accelerates
the prototyping process, saving time for the people involved in solving the
scientific problem. The ability to easily visualize problems with powerful
graphic libraries such as matplotlib and mayavi adds value to the quality
of the coding process because mistakes can be found more easily and they
can be presented in a better manner.
Being open source and modular in structure, Python provides the
ability to part-wise model develop faster by using existing code instead
of reinventing the wheel by writing it again. Within the same version of
Python (Python 2 or Python 3), the modules are compatible. Python also
allows codes of some languages to run natively within a Python code. Using
the Cython package, you can embed C code in a Python program. Similarly,
using the Jython package, you can embed java code in a Python program.
This allows programmers to choose various programming languages as
per their abilities and still develop their model in Python, taking advantage
of what their programming languages do not offer. This also enables
programmers to use legacy code instead of writing it again in Python.
239
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
In the age of the Internet, users might like to fetch data from database
servers, perform computation on a smaller chunk of data at a time, and
send back results to application servers for further processing and report
generation. For this purpose, Python provides a variety of packages.
Python has a standard mechanism for accessing databases called the
Database API (DB-API). The Python DB-API specifies a way to connect to
databases and issue commands to them. Python DB-API fits nicely into
existing Python code and allows Python programmers to easily store and
retrieve data from databases [2].
DB-API includes the following:
240
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
A large list of databases has been included in the DB-API list, which
enables developers to interact with multiple databases within a single code.
Specialized packages like pandas are designed to perform vectorized
operations on large datasets in an efficient manner. These are used
extensively nowadays in the field of big data. Most often, statistical analysis
is needed for a dataset. The pandas package provides most of the statistical
functions required for basic as well as advanced statistical analysis.
Coupled with simple plotting libraries like matplotlib, quick verification
of analysis and the ability to produce publication-quality graphs have
extended a golden helping hand to developers.
241
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
output) pins. Thus, using Python code, developers can read electrical signals
from sensors connected to RPi. Developers can also design complicated
electrical systems with actuators like motors connected to GPIO pins by
programming in Python to drive them. In most cases, scientific inputs
work in a feedback loop configuration where sensors read some physical
parameters, and these values are used to drive actuators to perform tasks.
Python can perform this task with ease. With this whole package being
defined under open source license, developers are free to reconfigure it in
any way desired. This enables scientists to develop customized equipment
as needed for their experiments.
In the case of hardware not running an OS, Python cannot directly access
the underlying hardware. It cannot interface directly with the software library
modules provided by most hardware vendors either. In these cases, Python
codes can be written to tap communication at a serial port or a USB device
that utilizes what is referred to as a virtual serial port. In these cases, there
are two options for developers: writing a C extension in the form of DLL
(dynamic-Link library) or using a ctypes library, which provides methods
to directly access function in external DLL. If DLL is already available via a
vendor, ctypes can access its functionalities within a Python code.
Another great module is PyVisa[3]. PyVisa is a Python package that
enables the developers to control all kinds of measurement devices
independently of the interface (for example, GPIB, RS232, USB, and
Ethernet). This is a great relief for complicated machines since a number of
different protocols are used to send data over many different interfaces and
bus systems (for instance, GPIB, RS232, USB, and Ethernet). Sometimes
the programming language that a developer wishes to use might not have
libraries that support both the device and its bus system. As a result, Virtual
Instrument Software Architecture (VISA) was devised. VISA is a standard
for configuring, programming, and troubleshooting instrumentation
systems comprising GPIB, VXI, PXI, Serial, Ethernet, and/or USB interfaces.
In any case, the responsibility of understanding the signal
output from electronic devices as well as managing data flow lies
242
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
243
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
10.10 Summary
The various features of Python that we have discussed prove that it is
a worthy candidate for an all-in-one solution for scientific tasks. Since
Python is open source, the vast number of libraries help to reduce
development times and costs. The availability to connect to databases of
large varieties, to hardwares of varied configurations, and to soures on
the Internet makes Python a favored option for scientific computation. In
this chapter, we have not ilustrated the usage of the individual module for
numerical computing and scientific work in general, but, instead, we have
convered various facilities due to the limitations of the scope of one book.
In this book, we have illustrated the usage of the Python3
programming language to a beginner, specifically targeting engineers
and scientists. Almost all branches of science and engineering requires
numerical computation. Python is one alternative to perform numerical
computation. Python has a library of optimized functions for general
computation. Also, it has a variety of packages to perform a specialized
job. This makes it an ideal choice for prototyping a numerical computation
problem efficiently. Moreover, it has thousands of libraries for specific
scientific tasks, both software- and hardware-oriented. For this reason,
Python is being taught at most university to students of engineering and
science. The community of developers is exponentially increasing. In the
near future, don’t be surprised if Python takes over the world!
244
CHAPTER 10 NUMERICAL COMPUTING FORMALISM
10.11 Bibliography
[1] https://pypi.python.org/pypi.
[2] https://www.python.org/dev/peps/pep-0249/.
[3] https://pyvisa.readthedocs.org/en/stable/.
245
Index
A mean(), median(),
and std(), 127
Ahead-of-time (AOT), 4
min() and max(), 127
Anaconda 2.4, 28
rounding off numbers, 129
Anaconda IDE
sort() sorts, 128
overview, 20
sum(), 126
Spyder IDE, 20
copies and views, 118
editor, 21
diagonal elements, 114
file explorer, 22
indexing, 114–116
help, 22
masking
IPython console, 21
fancy indexing, 120–121
variable explorer, 21
indexing, boolean arrays, 121
terminal, 25
matrices, 122
Arithmetic operators, 75–77
methods, 90
Arrays
ndarray, 89–90, 92
asarray() and asmatrix(), 130
numpy module, 87, 88
automatic creation
random numbers creation
empty(), 94
(see Random numbers
empty_like(), 95
creation)
eye(), 95
slicing, 116–118
full(), 98
tile() function, 111
full_like, 98
Assignment operator
identity(), 97
multiple assignments, =
ones() function, 93
operator, 73
ones_like(), 94
features, 70
zeros() function, 92
floating point number, 74
broadcasting, 112
print() function, 69
built-in operations
Python code, 68, 70
C
Class methods, 221–223
F, G
Class variables, 221–223 Floating point numbers, 66
Comparison operators, 79 Decimal() function, 54–55
Compiled languages, 18–19 double precision, 53
Complex numbers, 55–56 extended double precision, 53
Constructor, 223 float type, 51
Contour plots, 173–175 quadruple precision, 53
radix point, 52
real numbers, 51
D single precision, 53
Data types for loop, 191, 195–197, 199
character, 56 Frozensets, 59
comparison operators, 79 Functions
float(), 77 defining
int(), 77 block of statements, 189
lists and tuples, 58 descriptive string, 188
248
INDEX
I
Identity operator, 81 L
IEEE754, 53 List data types, 58
if-else loop, 199–200 Logarithmic plots
Infinite loops, 203–204 loglog() function, 171
Integer, 50 log.py, 168–169
Integrated development object mode capabilities,
environment (IDE) 168, 171
Anaconda (see Anaconda IDE) semilog() and semilogy(), 171
Spyder (see Spyder IDE) Logical operations
Interpreted language, 17, 19 boolean operators, 48–49
IPython, 25 complex statements, 49–50
commands, 33, 34 resultant of comparison, 50
console, 21 Loops
environment, 32 definition, 194
magic functions, 35 for loop, 195–197, 199
prompt, 33 if-else loop, 199–200
REPL, 34 infinite loops, 203–204
249
INDEX
250
INDEX
251
INDEX
252
INDEX
R Simulink, 10
Slicing, 116–118
Radix point, 52
Sorting algorithms, 129
Random numbers creation
Spyder IDE, 20, 47
normal (Gaussian)
editor, 21
distribution, 105–106
file explorer, 22
numpy.random.beta(), 104
help, 22
numpy.random.
IPython console, 21
binomial(n,p,size=), 105
variable explorer, 21
numpy.random.choice()
Strings, 56, 58
function, 102
Subplots, 161–162
numpy.random.permutation()
Symbolic computation
function, 103
(sympy), 25
numpy.random.shuffle(), 102
numpy.random subpackage, 106
random floating point T
numbers, 101 tile() function, 111
random integers, 100–101 Tuples, 58
Raspberry Pi (RPi), 9, 11, 241
Raw cell, 41
Read-Evaluate-Print-Loops U
(REPL), 2 Ubuntu, 15–16, 24–25
Rounding off numbers, 129
V
S Variables, 65–66
scatter() function-based Virtual environment (virtualenv)
plot, 161 activating, 29
Scipy stack, 25 create, 28
Sequences deactivating, 29–30
lists and tuples, 58 install, 28
strings, 56, 58 Virtual Instrument Software
Set data type, 59 Architecture (VISA), 242
253
INDEX
W, X, Y Z
while-else loop, 204–205 The Zen of Python, 6
while loop, 201–203
Windows, 14–15
Wiremesh and surface
plots, 177, 179–181
254