Introduction To Python For Science and Engineering 1st Edition David J. Pine - Quickly Access The Ebook and Start Reading Today
Introduction To Python For Science and Engineering 1st Edition David J. Pine - Quickly Access The Ebook and Start Reading Today
com
https://textbookfull.com/product/introduction-to-python-for-
science-and-engineering-1st-edition-david-j-pine/
OR CLICK HERE
DOWLOAD EBOOK
https://textbookfull.com/product/data-science-fundamentals-for-python-
and-mongodb-1st-edition-david-paper/
textbookfull.com
https://textbookfull.com/product/introduction-to-linear-algebra-for-
science-and-engineering-daniel-norman/
textbookfull.com
https://textbookfull.com/product/introduction-to-quantum-mechanics-
david-j-griffiths/
textbookfull.com
https://textbookfull.com/product/introduction-to-linear-algebra-for-
science-and-engineering-3rd-edition-daniel-norman/
textbookfull.com
Introduction to Electrodynamics Fourth Edition David J.
Griffiths
https://textbookfull.com/product/introduction-to-electrodynamics-
fourth-edition-david-j-griffiths/
textbookfull.com
https://textbookfull.com/product/introduction-to-computing-and-
programming-in-python-global-edition-mark-j-guzdial/
textbookfull.com
https://textbookfull.com/product/python-programming-an-introduction-
to-computer-science-john-m-zelle/
textbookfull.com
https://textbookfull.com/product/sf1624-algebra-and-geometry-
introduction-to-linear-algebra-for-science-engineering-daniel-norman/
textbookfull.com
https://textbookfull.com/product/introduction-to-software-
engineering-2nd-edition-ronald-j-leach/
textbookfull.com
Introduction to
Python for Science
and Engineering
Series in Computational Physics
Parallel Science and Engineering Applications: The Charm++ Approach
Laxmikant V. Kale, Abhinav Bhatele
David J. Pine
MATLAB® is a trademark of The MathWorks, Inc. and is used with permission. The MathWorks
does not warrant the accuracy of the text or exercises in this book. This book’s use or discussion
of MATLAB® software or related products does not constitute endorsement or sponsorship by The
MathWorks of a particular pedagogical approach or particular use of the MATLAB® software.
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts
have been made to publish reliable data and information, but the author and publisher cannot assume
responsibility for the validity of all materials or the consequences of their use. The authors and publishers
have attempted to trace the copyright holders of all material reproduced in this publication and apologize
to copyright holders if permission to publish in this form has not been obtained. If any copyright material
has not been acknowledged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, trans-
mitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter
invented, including photocopying, microfilming, and recording, or in any information storage or retrieval
system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.
com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood
Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and
registration for a variety of users. For organizations that have been granted a photocopy license by the
CCC, a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are
used only for identification and explanation without intent to infringe.
Preface xv
1 Introduction 1
1.1 Introduction to Python for Science and Engineering . 1
2 Launching Python 3
2.1 Interacting with Python . . . . . . . . . . . . . . . . . 3
2.2 Installing Python on Your Computer . . . . . . . . . . 4
2.3 The Spyder Window . . . . . . . . . . . . . . . . . . . 4
2.4 The IPython Pane . . . . . . . . . . . . . . . . . . . . . 4
2.4.1 Magic commands . . . . . . . . . . . . . . . . . 6
2.4.2 System shell commands . . . . . . . . . . . . . 8
2.4.3 Tab completion . . . . . . . . . . . . . . . . . . 8
2.4.4 Recap of commands . . . . . . . . . . . . . . . . 9
2.5 Interactive Python as a Calculator . . . . . . . . . . . 9
2.5.1 Binary arithmetic operations in Python . . . . . 10
2.5.2 Types of numbers . . . . . . . . . . . . . . . . . 10
2.5.3 Important note on integer division in Python . 12
2.6 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.6.1 Names and the assignment operator . . . . . . 13
2.6.2 Legal and recommended variable names . . . . 14
2.6.3 Reserved words in Python . . . . . . . . . . . . 15
2.7 Script Files and Programs . . . . . . . . . . . . . . . . 16
2.7.1 First scripting example: The Editor pane . . . . 16
2.8 Python Modules . . . . . . . . . . . . . . . . . . . . . . 18
2.8.1 Python modules and functions: A first look . . 20
2.8.2 Some NumPy functions . . . . . . . . . . . . . . 22
2.8.3 Scripting Example 2 . . . . . . . . . . . . . . . 23
2.8.4 Different ways of importing modules . . . . . . 24
2.9 Getting Help: Documentation in IPython . . . . . . . 26
vii
viii Contents
6 Plotting 99
6.1 An Interactive Session with PyPlot . . . . . . . . . . . 100
6.2 Basic Plotting . . . . . . . . . . . . . . . . . . . . . . . 102
6.2.1 Specifying line and symbol types and colors . . 106
6.2.2 Error bars . . . . . . . . . . . . . . . . . . . . . 108
6.2.3 Setting plotting limits and excluding data . . . 110
6.2.4 Subplots . . . . . . . . . . . . . . . . . . . . . . 113
6.3 Logarithmic Plots . . . . . . . . . . . . . . . . . . . . . 116
6.3.1 Semi-log plots . . . . . . . . . . . . . . . . . . . 116
6.3.2 Log-log plots . . . . . . . . . . . . . . . . . . . . 118
6.4 More Advanced Graphical Output . . . . . . . . . . . 118
6.4.1 An alternative syntax for a grid of plots . . . . 122
6.5 Plots with multiple axes . . . . . . . . . . . . . . . . . 125
6.6 Mathematics and Greek symbols . . . . . . . . . . . . 126
6.7 The Structure of matplotlib: OOP and All That . . . . 131
6.7.1 The backend layer . . . . . . . . . . . . . . . . . 132
6.7.2 The artist layer . . . . . . . . . . . . . . . . . . . 135
6.7.3 The PyPlot (scripting) layer . . . . . . . . . . . 137
6.8 Contour and Vector Field Plots . . . . . . . . . . . . . 139
6.8.1 Making a 2D grid of points . . . . . . . . . . . . 139
6.8.2 Contour plots . . . . . . . . . . . . . . . . . . . 140
6.8.3 Streamline plots . . . . . . . . . . . . . . . . . . 144
6.9 Three-Dimensional Plots . . . . . . . . . . . . . . . . . 149
6.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . 152
7 Functions 155
7.1 User-Defined Functions . . . . . . . . . . . . . . . . . 156
7.1.1 Looping over arrays in user-defined functions . 158
x Contents
11 Animation 287
11.1 Animating a Sequence of Images . . . . . . . . . . . . 287
11.1.1 Simple image sequence . . . . . . . . . . . . . . 288
11.1.2 Annotating and embellishing videos . . . . . . 292
11.2 Animating Functions . . . . . . . . . . . . . . . . . . . 294
11.2.1 Animating for a fixed number of frames . . . . 295
11.2.2 Animating until a condition is met . . . . . . . 300
11.3 Combining Videos with Animated Functions . . . . . 306
xii Contents
C Glossary 355
Contents xiii
Index 363
Preface
xv
xvi Introduction to Python for Science & Engineering
David Pine has taught physics and chemical engineering for over 30
years at four different institutions: Cornell University (as a graduate
student), Haverford College, UCSB, and, at NYU, where he is a Profes-
sor of Physics, Mathematics, and Chemical & Biomolecular Engineer-
ing. He has taught a broad spectrum of courses, including numerical
methods. He does research in experimental soft-matter physics, which
is concerned with materials such as polymers, emulsions, and col-
loids. These materials constitute most of the material building blocks
of biological organisms.
xix
chapter 1
Introduction
1
2 Introduction to Python for Science & Engineering
This also means that you can use Python without being tethered to
the internet, as required for commercial software that is tied to a re-
mote license server.
Another advantage is Python’s clean and simple syntax, including
its implementation of object-oriented programming. This should not
be discounted; Python’s rich and elegant syntax renders a number of
tasks that are difficult or arcane in other languages either simpler or
more understandable in Python.
An important disadvantage is that Python programs can be slower
than compiled languages like C. For large-scale simulations and other
demanding applications, there can be a considerable speed penalty in
using Python. In these cases, C, C++, or Fortran is recommended, al-
though intelligent use of Python’s array processing tools contained in
the NumPy module can greatly speed up Python code. Another dis-
advantage is that, compared to MATLAB® , Python is less well docu-
mented. This stems from the fact that it is public open source software
and thus is dependent on volunteers from the community of develop-
ers and users for documentation. The documentation is freely avail-
able on the web but is scattered among a number of different sites and
can be terse. This manual will acquaint you with the most commonly
used web sites. Search engines like Google can help you find others.
You are not assumed to have had any previous programming ex-
perience. However, the purpose of this manual isn’t to teach you the
principles of computer programming; it’s to provide a very practical
guide to getting started with Python for scientific computing. Perhaps
once you see some of the powerful tasks that you can accomplish with
Python, you will be inspired to study computational science and en-
gineering, as well as computer programming, in greater depth.
chapter 2
Launching Python
3
4 Introduction to Python for Science & Engineering
This prompt signifies that Spyder is running the IPython shell. The
IPython shell has been specifically designed for scientific and engi-
Launching Python 5
Help Pane
Editor Pane
IPython Pane
neering use. The standard Python interactive shell uses the prompt
>>>. You can pretty much do everything you want to do with either
shell, but we will be using the IPython shell as we want to take ad-
vantage of some of its special features for scientific computing.
By typing commands at the prompt, IPython can be used to per-
form various system tasks, such as running programs and creating
and moving files around on your computer. This is a different kind
of computer interface than the icon-based interface (or graphical user
interface, GUI) that you usually use to communicate with your com-
puter. While it may seem more cumbersome for some tasks, it can
be more powerful for other tasks, particularly those associated with
programming.
Before getting started, we point out that like most modern com-
puter languages, Python is case sensitive. That is, Python distinguishes
between upper- and lower-case letters. Thus, two words spelled the
same but having different letters capitalized are treated as different
names in Python. Keep that in mind as we introduce different com-
mands.
6 Introduction to Python for Science & Engineering
Navigation commands
IPython recognizes several common navigation commands that are
used under the Unix/Linux operating systems. In the IPython shell,
these few commands work on Macs, PCs, and Linux machines.
At the IPython prompt, type %cd ∼ (i.e., “%cd” – “space” – “tilde”,
where tilde is found near the upper left corner of most keyboards).
This will set your computer to its home (default) directory.
In [1]: %cd ~
/Users/pine
Next type %pwd (print working directory) and press Return. The con-
sole should return the path of the current directory of your computer.
It might look like this on a Mac:
In [2]: %pwd
Out[2]: '/Users/pine'
or this on a PC:
In [3]: %pwd
Out[3]: C:\\Users\\pine
Typing %cd .. (“%cd” – “space” – two periods) moves the IPython shell
up one directory in the directory tree, as illustrated by the set of com-
mands below.
In [4]: %cd ..
/Users
Launching Python 7
In [5]: %pwd
Out[5]: '/Users'
In this case, there are only two directories (indicated by the slash) and
no files (although the names of the files may be different for you).
Type %cd ∼ again to return to your home directory and then type pwd
to verify where you are in your directory tree.
Making a directory
Let’s create a directory within your documents directory that you can
use to store your Python programs. We will call it programs. First, re-
turn to your home directory by typing %cd ~. Then type %ls to list the
files and directories in your home directory.
In [7]: %cd ~
/Users/pine
In [8]: %ls
Applications/ Library/ Pictures/
Desktop/ Movies/ Public/
Documents/ Music/
Downloads/ News/
In [10]: %ls
Applications/ Library/ Pictures/
Desktop/ Movies/ Public/
Documents/ Music/ programs/
Downloads/ News/
You should see that a new directory named programs has been added
to the list of directories. Next, type %cd programs to navigate to that
new directory.
In [11]: %cd programs
/Users/pine/programs
8 Introduction to Python for Science & Engineering
THE MARTIN.
The MARTIN or ROOF SWALLOW (Chelidon urbica) we have selected as
the type of a group, recognisable by their slightly forked tail and
strong feet, the toes of which are connected from the first joint, and,
like the tarsi, are thickly covered with feathers. This bird is five
inches and a half long, and ten and three-quarters broad; the wing
measures four inches, and the tail two and a half. Upon the back the
plumage is almost entirely of an uniform blueish black; the under
side and rump are white. The eye is dark brown, the beak black, and
the bare parts of the foot black. Both sexes are alike in colour, but
the plumage of the young is less clear in its tints than that of the
adult. The Martin inhabits the whole of Europe, and penetrates
further north than the Chimney Swallow; it is numerous in Siberia,
and during its migrations visits the interior of Africa and Southern
Asia. In most respects it closely resembles the species already
described, but is somewhat less brisk and intelligent; its flight also is
not so rapid and varied as that of the Chimney Swallow, but it
frequently soars to an enormous height in pursuit of the insects
upon which it subsists. Its voice is very far inferior to that of the rest
of its family, and its cry monotonous and harsh.
In populous districts the nests of this bird are invariably constructed
upon houses, but where human habitations are scarce, the Roof
Swallow is content to make its preparations upon rocks, or any
situation that will afford it a secure shelter from the wind and rain.
The nest is very similar to that of the Chimney Swallow, but with this
difference, that it is always built against a hole, and has no external
entrance; sometimes many pairs construct their dwellings under the
same eaves or the same rock, and thus form a kind of settlement.
Although usually peaceful, during the breeding season disputes and
battles are of constant occurrence; each couple naturally
endeavouring to obtain the snuggest corner, and to oust its
neighbour should the opportunity offer. The brood consists of from
four to six delicate snow-white eggs, and the nestlings are hatched
in about twelve days. The female alone broods, and is fed by her
mate only when the weather is fine; the young also frequently have
but an insufficient supply of food, owing to the difficulty of procuring
insects when the season is inclement, and thus must very often be
left behind when the flocks migrate, as they are still too weak to
undergo such great fatigue. If all goes well, the nestlings are fully
fledged in about sixteen days, but generally remain for some time
longer under the care of their parents. During this period the whole
family return at night to their nest, which they fill so completely that
we have often been inclined to wonder that the walls did not give
way under the pressure to which they were subjected. Desperate
fights often ensue when a stray bird finds its way into a wrong nest,
and most courageously do those in possession exert themselves to
expel the intruder, who is generally equally determined to remain.
Far less brave is the Swallow when brought into collision with its
principal enemy, the Sparrow; it often happens that no sooner is the
Swallow's nest completed than a male Sparrow creeps in and takes
possession, keeping guard at the door, in order to prevent the
entrance of the rightful owner; under these circumstances, the latter,
not venturing to obtain admittance by force, usually summons its
companions, who together beset the impudent intruder with loud
cries and every demonstration of anger. In most cases the Sparrow
retains possession of its ill-gotten abode, but should the Swallow be
bold, a battle sometimes takes place that proves fatal to one or
other of the combatants. So constant are these attempts of the
Sparrow to obtain a home for its young, that a pair of Swallows
sometimes are deprived twice in the season of the domicile they
have laboriously completed, and, should this occur, do not breed at
all that year. It was formerly imagined that the Swallow revenged
itself on its foe by building it up in the nest, but we need hardly say
that this is untrue.
The Martins make their appearance in England a few days after the
Chimney Swallow (Cecropis-Hirundo-rustica), and on their arrival are
usually seen in warm and low situations, such being most likely to
supply an abundance of their natural food. They are equally
distributed throughout the kingdom, and are found wherever man
has fixed his residence, seeming to court his protection. They
commence nidification early in May, and build in the upper angles of
windows and under the eaves of houses, sometimes under the
arches of bridges or against the face of rocks. The nest is formed of
mud completely worked and cemented, and is closed all round
except a small orifice, usually on the sheltered side, just of sufficient
size to permit the passage of the inhabitant; the interior is well lined
with a collection of straw, hay, and feathers. These birds leave us in
October; preparatory to their departure, they congregate in great
numbers on the roofs of houses.
The MOUNTAIN or SHORE SWALLOWS (Cotyle) are recognisable by
their slightly forked tail, and lax, lustreless plumage. Two species are
indigenous to Europe; a description of these will serve for the entire
group.
The WOOD SWALLOWS (Atticora) are delicate birds with long wings
(in which the first and second quills are of equal length), forked tails,
thin beaks, and slender legs, furnished with short toes; the plumage
gleams with metallic lustre, and is much varied in its hues. All the
species included in this group inhabit South America and Africa; they
frequent woods and forests, and build their nests in the trunks of
hollow trees.
THE STRIPED WOOD SWALLOW.
The STRIPED WOOD SWALLOW (Atticora fasciata) is a native of Brazil. Its
plumage is black, marked with white upon the breast and under part
of the thigh; the rump has a blueish gloss. The length of the body is
six inches, the wing measures four, and the tail three inches. This
active, lively bird frequents the forests of Northern Brazil, from
whence it flies, in search of its insect fare, over the neighbouring
streams and rivers, and perches or sleeps amongst the surrounding
trees.
All such species as inhabit the temperate zone migrate with the
utmost regularity as winter approaches, and return to their native
haunts with such unfailing precision that the day on which they will
re-appear may be accurately prognosticated. Those species
inhabiting the interior of Africa never actually migrate, but occupy
themselves in flying over the face of the country during the wet
season. The work of constructing the nest is commenced as soon as
the winter journeyings are over, and is always carried on amidst
great excitement; the males chasing and fighting each other most
furiously during the whole time, and constantly engaging in pitched
battles with the birds whose nests they prefer taking rather than
undergo the labour of constructing a home for themselves. Unlike
the nests of the Swallows, those built by the Swifts seldom consist of
more than a few slight materials laid carelessly together, and
cemented with saliva from the builder's beak. The eggs are round
and white; the female alone broods, but both parents share in the
toil of satisfying their hungry progeny.
SALANGANES.
THE KLECHO.
The KLECHO (Dendrochelidon klecho), so called from the sound of its
cry, is about seven inches long; the wing measures six, and the tail
three inches. Upon the upper part of the body the plumage is of a
brilliant metallic steel-green; the wing-covers have a blueish lustre;
the quills are blackish on the inner and blue on the outer web, and
the shoulder-feathers white. The belly is white, the rest of the under
surface and rump of a beautiful deep grey. The male has a reddish
brown and the female a black spot near the eye.
The Tree Swifts differ almost entirely in their mode of life from any
other members of their family. Extensive woods and dense forests
are their favourite resorts, such being preferred as are in lowland
districts; according to Jerdon, the Indian Klecho constantly builds in
these localities, flying from thence over the streams or lakes in the
vicinity in search of insects on which it subsists. Whilst resting from
its labours it usually selects a withered tree for its perch, and
amuses itself by expanding and playing with the beautiful crest upon
its head. Its flight is excellent, but it climbs awkwardly among the
branches. When upon the wing it utters almost incessantly a loud
parrot-like scream; when perched its voice is not quite so harsh. We
learn from Bernstein that, unlike all other Swifts, the Klecho usually
builds at the summit of a tree, upon a branch of about an inch in
thickness. Its strange nest, the walls of which are scarcely thicker
than parchment, is constructed of bits of bark, feathers, and other
similar materials, woven together, and cemented with saliva. The
great peculiarity of the nest consists in the fact that it is only just big
enough to contain the one large egg laid by the female, and that the
walls are far too delicate to bear the weight of the brooding mother;
the bird is, therefore, compelled to perch and support herself upon
the branch, and merely allow her breast to cover and warm her
offspring. The female lays twice in the season; the egg is perfectly
oval and of a blueish tint.
THE KUSAPPI.
THE WHITE-THROATED PRICKLY-TAILED SWIFT (Acanthylis caudacuta).
THE NACUNDA.
The NACUNDA (Podager nacunda) has obtained its name from the
unusual size of its mouth, and may be regarded as the type of a
South American group, distinguished by their powerful body, very
broad head, strong beak, and thick plumage; their beak curves
slightly downwards at its tip, and the mouth is surrounded by a
growth of very stiff, short bristles; the nostrils are situated
immediately above the upper mandibles. The wings, in which the
second and third quills exceed the rest in length, are long and
pointed; the short tail is composed of broad feathers and slightly
rounded at its tip. The legs are powerful, the tarsi long and bare, the
toes fleshy, and the nail of the middle toe serrated. The plumage of
the Nacunda on the upper part of the body is blackish brown,
marked with fine reddish yellow lines; the head is darker than the
middle of the back, and the region of the shoulder indicated by large
blackish brown spots. The tail-feathers exhibit six or eight dark lines,
those of the male being edged with white. The throat, cheek-stripes,
and region of the ear are reddish yellow, and slightly spotted; the
belly, legs, lower tail-covers, and a line which passes from ear to ear
around the throat are of a pure white; the breast is marked with
undulating lines. The very large eyes are light brown; the beak
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com