SlideShare a Scribd company logo
Computing With Python An Introduction To Python
For Science Engineering Claus Fuher download
https://ebookbell.com/product/computing-with-python-an-
introduction-to-python-for-science-engineering-claus-
fuher-5903416
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Computing With Python An Introduction To Python For Science And
Engineering Feuhrer
https://ebookbell.com/product/computing-with-python-an-introduction-
to-python-for-science-and-engineering-feuhrer-22059306
Computational Mathematics An Introduction To Numerical Analysis And
Scientific Computing With Python Dimitrios Mitsotakis
https://ebookbell.com/product/computational-mathematics-an-
introduction-to-numerical-analysis-and-scientific-computing-with-
python-dimitrios-mitsotakis-50292792
An Introduction To Scientific Computing With Matlab And Python
Tutorials Sheng Xu
https://ebookbell.com/product/an-introduction-to-scientific-computing-
with-matlab-and-python-tutorials-sheng-xu-42864256
Scientific Computing With Python 3 An Examplerich Comprehensive Guide
For All Of Your Python Computational Needs 1st Edition Claus Fuhrer
Jan Erik Solem Olivier Verdier
https://ebookbell.com/product/scientific-computing-with-python-3-an-
examplerich-comprehensive-guide-for-all-of-your-python-computational-
needs-1st-edition-claus-fuhrer-jan-erik-solem-olivier-verdier-32704550
Distributed Computing With Python Pierfederici Francesco
https://ebookbell.com/product/distributed-computing-with-python-
pierfederici-francesco-22066648
Scientific Computing With Python Highperformance Scientific Computing
With Numpy Scipy And Pandas 2nd Edition Claus Fuhrer Jan Erik Solem
Olivier Verdier
https://ebookbell.com/product/scientific-computing-with-python-
highperformance-scientific-computing-with-numpy-scipy-and-pandas-2nd-
edition-claus-fuhrer-jan-erik-solem-olivier-verdier-33789050
Numerical Computing With Python Harness The Power Of Python To Analyze
And Find Hidden Patterns In The Data 1st Edition Pratap Dangeti Allen
Yu Claire Chung Aldrin Yim Theodore Petrou
https://ebookbell.com/product/numerical-computing-with-python-harness-
the-power-of-python-to-analyze-and-find-hidden-patterns-in-the-
data-1st-edition-pratap-dangeti-allen-yu-claire-chung-aldrin-yim-
theodore-petrou-7351196
Scientific Computing With Python Mastering Numpy And Scipy 1st Edition
John Smith
https://ebookbell.com/product/scientific-computing-with-python-
mastering-numpy-and-scipy-1st-edition-john-smith-58531304
Scientific Computing With Python 2nd Edition 2nd Claus Fhrer
https://ebookbell.com/product/scientific-computing-with-python-2nd-
edition-2nd-claus-fhrer-51012512
Computing With Python An Introduction To Python For Science Engineering Claus Fuher
CiausFiihrer Jan Erik Solem Olivier Verdier
COMPUTING
WITH PYTHON
An introduction to Python for science and engineering
v M
-5 >-«
>•-, -
> -
t - *
X
> 5C
J
*c >
>
p -
s
V
p CP'
*
■*a*
*
05
ALWAYS LEARNING PEARSON
COMPUTING WITH PYTHON
AN INTRODUCTION TO PYTHON FOR
SCIENCE AND ENGINEERING
PEARSON
At Pearson, we take learning personally. Our courses and
resources are available as books, online and via multi-lingual
packages, helping people learn whatever, wherever and
however they choose.
We work with leading authors to develop the strongest
learning experiences, bringing cutting-edge thinking and best
learning practice to a global market. We craft our print and
digital resources to do more to help learners not only
understand their content, but to see it in action and apply
what they learn, whether studying or at work.
Pearson is the world's leading learning company. Our portfolio
includes Penguin, Dorling Kindersley, the Financial Times and
our educational business, Pearson International. We are also
a leading provider of electronic learning programmes and
of test development, processing and scoring services to
educational institutions, corporations and professional bodies
around the world.
Every day our work helps learning flourish, and wherever
learning flourishes, so do people.
To learn more please visit us at: www.pearson.com/uk
COMPUTING WITH
PYTHON
AN INTRODUCTION TO PYTHON
FOR SCIENCE AND ENGINEERING
Claus Fuhrer, Jan Erik Solem and
Olivier Verdier
PEARSON
Harlow, England • London • New York • Boston • San Francisco • Toronto • Sydney • Auckland • Singapore • Hong Kong
Tokyo • Seoul • Taipei • New Delhi • Cape Town • Sao Paulo • Mexico City • Madrid • Amsterdam • Munich • Paris • Milan
PEARSON EDUCATION LIMITED
Edinburgh Gate
Harlow CM20 2JE
United Kingdom
Tel: +44 (0)1279 623623
Web; www.pearson.com/uk
First published 2014 (print and electronic)
© Pearson Education Limited 2014 (print and electronic)
The rights of Glaus Fiihrer, Jan Erik Solem and Olivier Verdier to be identified as authors of this work
have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988.
The print publication is protected by copyright. Prior to any prohibited reproduction, storage in a
retrieval system, distribution or transmission in any form or by any means, electronic, mechanical,
recording or otherwise, permission should be obtained from the publisher or, where applicable, a licence
permitting restricted copying in the United Kingdom should be obtained from the Copyright Licensing
Agency Ltd, Saffron House, 6-10 Kirby Street, London EC1N 8TS.
The ePublication is protected by copyright and must not be copied, reproduced, transferred,
distributed, leased, licensed or publicly performed or used in any way except as specifically permitted in
writing by the publishers, as allowed under the terms and conditions under which it was purchased, or
as strictly permitted by applicable copyright law. Any unauthorised distribution or use of this text may be
a direct infringement of the author's and the publishers' rights and those responsible may be liable in
law accordingly.
All trademarks used herein are the property of their respective owners. The use of any trademark in this
text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor
does the use of such trademarks imply any affiliation with or endorsement of this book by such owners.
'Python' is a registered trademark of the Python Software Foundation.
Pearson Education is not responsible for the content of third-party internet sites.
ISBN: 978-0-273-78643-6 (print)
British Library Cataloguing-in-Publication Data
A catalogue record for the print edition is available from the British Library
Library of Congress Cataloging-in-Publication Data
Fuhrer, Glaus.
Computing with Python : an introduction to Python for science and engineering / Glaus Fuhrer, Jan Erik
Solem and Olivier Verdier.
pages cm.
Includes bibliographical references and indexes.
ISBN 978-0-273-78643-6 (print: alkaline paper)
1. Python (Computer program language) 2. Science-Data processing. 3. Engineering-Data processing.
I. Solem, Jan Erik. II. Verdier, Olivier. III. Title.
QA76.73.P98F84 2013
005.13'3-dc23
2013025146
10 987654321
16 15 14 13
Print edition typeset in Stone Serif 9/11.5 by 73
Print edition printed and bound in Malaysia
NOTE THAT ANY PAGE CROSS REFERENCES REFER TO THE PRINT EDITION
BRIEF CONTENTS
Contents vii Chapter X Iterating 133
Preface ix
Chapter XI Error Handling 150
Chapter 1 Introduction 1
Chapter XII Namespaces, Scopes
Chapter II Getting Started 6 and Modules 162
Chapter III Variables and Basic Types 14 Chapter XIII Input and Output 168
Chapter IV Container Types 30 Chapter XIV Testing 175
Chapter V Linear Algebra: Arrays 44 Chapter XV Comprehensive Examples 189
Chapter VI Advanced Array Concepts 65 Appendix; Calling MATLAB from Python 203
Chapter VII Plotting 84
Bibliography
Python commands index
206
208
Chapter VIM Functions 101 Subject index 210
Chapter IX Classes 114
This page intentionally left blank
Contents vii V.8 Functions Acting on Arrays 57
Preface ix V.9 Linear Algebra Methods in SciPy
V.10 Exercises
60
62
Chapter 1 Introduction 1
1.1 Python vs Other Languages 1
Chapter VI Advanced Array Concepts 65
1.2 Literature 3 VI.1 Array Views and Copies 65
I.3 Installation and Configuration Instructions 3 VI.2 Comparing Arrays 66
1.4 Executing Scripts 4 VI.3 Array Indexing
VI.4 Performance and Vectorization
69
71
Chapter II Getting Started 6 VI.5 Broadcasting 73
VI.6 Sparse Matrices 79
II.1 Program and Program Flow 6
11.2 Basic Types
11.3 Loops
7
10
Chapter VII Plotting 84
11.4 Conditional Statements 11 VII.1 Basic Plotting 84
11.5 Functions 11 VII.2 Formatting 87
11.6 Scripts and Modules 12 VII.3 Images and Contours 91
11.7 Interpreter 13 VII.4 Useful Toolkits
VI1.5 Exercises
93
99
Chapter III Variables and Basic Types 14
111.1 Variables 14
Chapter VIII Functions 101
III.2 Numeric Types 15 VIII.1 Basics 101
III.3 Booleans 21 VIII.2 Parameters and Arguments 102
III.4 Strings 24 VIII.3 Return Values 106
III.5 Exercises 27 VIII.4 Recursive Functions
VIII.5 Function Documentation
107
108
Chapter IV Container Types 30 VIII.6 Functions are Objects 109
VIII.7 Anonymous Functions - the lambda
IV.I Lists 30 Keyword 110
IV.2 Arrays 36 VIII.8 Functions as Decorators 112
IV.3 Tuples 37 VIII.9 Exercises 113
IV.4 Dictionaries 38
IV.5 Sets
IV.6 Container Conversions and Summary
40
41
Chapter IX Classes 114
IV.7 Type Checking 41 IX.1 Introduction 115
IV.8 Exercises 42 IX.2 Attributes
IX.3 Subclassing and Inheritance
116
126
Chapter V Linear Algebra: Arrays 44 IX.4 Encapsulation 128
IX.5 Classes as Decorators 129
V.I Overview 44 IX.6 Exercises 131
V.2 Mathematical Preliminaries 47
V.3 The Array Type
V.4 Array Indexing
49
51
Chapter X Iterating 133
V.5 Functions to Construct Arrays 53 X.1 The for statement 133
V.6 Accessing and Changing the Shape 53 X.2 Iterators 135
V.7 Stacking 56
VIII Contents
X.3 List Filling Patterns 141
X.4 When Iterators Behave as Lists 144
X.5 Iterator Objects 145
X.6 Infinite Iterations 146
X.7 Exercises 148
Chapter XI Error Handling 150
XI.1 Exceptions 150
XI.2 Debugging 157
Chapter XII Namespaces,
Scopes and Modules 162
XII.1 Namespace 162
XII.2 Scope of a Variable 163
XII.3 Modules 164
Chapter XIII Input and Output 168
XIII.1 File Handling 168
XIII.2 NumPy Methods 170
XIII.3 Pickling 171
XIII.4 Shelves 172
XIII.5 Reading and Writing Matlab Data Files 173
XIII.6 Reading and Writing Images 173
Chapter XIV Testing 175
XIV. 1 Manual Testing 175
XIV.2 Automatic Testing 176
XIV.3 Measuring Execution Time 184
XIV.4 Exercises 188
Chapter XV Comprehensive Examples 189
XV.1 Polynomials 189
XV.2 Spectral Clustering 196
XV.3 Solving Initial Value Problems 199
XV.4 Exercises 202
Appendix: Calling MATLAB from Python 203
Bibliography 206
Python commands index 208
Subject index 210
PREFACE
This book is the outcome of a course on Python® for scientific computing which has been
taught at Lund University since 2008. The course expanded over the years, and condensed
versions of the material were taught at universities in Cologne, Trondheim, Stavanger,
Soran and also in computational oriented companies.
Our belief is that Python and its surrounding scientific computing ecosystem - SciPy,
NumPy and matplotlib - represent tremendous progress in the scientific computing en-
vironment. Python and the aforementioned libraries are free and open source. What's
more, Python is a modern language featuring all the bells and whistles that this adjective
entails: object oriented programing, testing, advanced Python shell with IPython, etc.
The typical reader of this book will already have some experience in programing, and
some taste for scientific computing or mathematics. Our goal is to explain to those readers
the steps to get started with Python in the context of scientific computing. The book
may be read either from the first page to the last, or by picking the bits that seem most
interesting. Needless to say, as improving one's programing skills requires considerable
practice, it is highly advisable to experiment and play with the examples and the exercises
in the book.
We hope that readers will enjoy programing with Python, SciPy, NumPy and matplotlib
as much as we do.
We would like to express our gratitude towards the reviewers of this book: Linda Kann,
KTH Stockholm, Hans Petter Langtangen, Simula Research Laboratory, and Alf Inge Wang,
NTNU Trondheim.
This book benefited from many helpful comments and suggestions by Helmut Pod-
haisky, Halle University, Tony Stillfjord and Christian Andersson, Lund University, and
students and teaching assistants from the course 'Berakningsprogramering med Python'
over the years.
Finally, we would like to express our thanks for the fruitful collaboration with the pub-
lisher during the production process, in particular to Philippa Fiszzon.
The Authors
September 27, 2013
This page intentionally left blank
CHAPTER I
Introduction
1.1 Python vs Other Languages
When it comes to deciding what language to use for a book on scientific computing many
factors come in to play. The learning threshold of the language itself is important for
newcomers, here scripting languages usually provide the best options. A wide range of
modules for numerical computing is necessary, preferably with a strong developer com-
munity. If these core modules are built on a well-tested, optimized foundation of fast
libraries like e.g. LAPACK, even better. Finally, if the language is also usable in a wider
setting and a wider range of applications, the chance of the reader using the skills learned
from this book outside an academic setting is greater. Therefore the choice of Python was a
natural one.
In short, Python is
• free and open source
• a scripting language, meaning that it is interpreted
• a modern language (object oriented, exception handling, dynamic typing etc.)
• concise, easy to read and quick to learn
• full of freely available libraries, in particular scientific ones (linear algebra, visualiz-
ation tools, plotting, image analysis, differential equations solving, symbolic compu-
tations, statistics etc.)
• useful in a wider setting: scientific computing, scripting, web sites, text parsing, etc.
• widely used in industrial applications
1.1.1 Python vs other languages
There are other alternatives to Python. Some of them and the differences to Python are
listed here.
Java, C++ Object oriented, compiled languages. More verbose and low level com-
pared to Python. Few scientific libraries.
c, Fortran Low level compiled languages. Both languages are extensively used in
scientific computing, where computational time matters. Nowadays these languages
are often combined with Python wrappers.
php, ruby Other interpreted languages. PHP is web oriented. Ruby is as flexible as
Python but has few scientific libraries.
matlab, SciLab, Octave MATLAB is a tool for matrix computation that evolved
for scientific computing. The scientific library is huge. The language features are not
Chapter I Introduction
as developed as those of Python. Neither free nor open source. SciLab and Octave are
open source tools which are syntacticly similar to MATLAB.
Haskell Haskell is a modern functional language and follows different programing
paradigms than Python. There are some common constructions like list comprehen-
sion. Haskell is rarely used in scientific computing. See also [11].
1.1.2 Examples
Python is a scripting language that may be used in interactive mode, meaning that you type
commands at a prompt:
»> x = 3
>» y = 5
»> print (x + y)
8
Here we solve the system of equations
G TT)
using SciPy:
»> import scipy. linalg as si
»> M = array ([[!., 2 . ] ,
[3., 4.]])
»> V = array ( [2 . , 1. ] )
»> x = si. solve (M, V)
»> print (x)
[-3. 2.5]
Computing el7r
and 2100
is another example:
»> print (exp (Ij *pi) ) # should return -1
(-1+ 1.22464679915e-16j )
»> print (2**100)
1267650600228229401496703205376L
So is computing t;(x) — F- ^or
= 2 we
know that ^(2) = ^:
# for x = 2:
»> print (scipy . special. zeta (2 . , 1))
1.64493406685
»> print (pi**2/6)
1.6449340668482264
These examples are meant as a teaser and to give you a sense of the language that we will
be exploring in this book.
1.3 Installation and Configuration Instructions
1.2 Literature
Here we give some hints to literature on Python which can serve as complementary sources
or as texts for parallel reading. Most introductory books on Python are devoted to teach
this language as a general purpose tool. One excellent example which we want to men-
tion explicitly is [18]. It explains the language by simple examples, e.g. object oriented
programing is explained by organizing a pizza bakery.
There are very few books dedicated to Python directed towards scientific computing
and engineering. Among these few books we would like to mention the two books by
Langtangen which combine scientific computing with the modern "pythonic" view on
programing, [15, 16].
This "pythonic" view is also the guiding line of our way of teaching programing of
numerical algorithms. We try to show how many well-established concepts and construc-
tions in computer science can be applied to problems within scientific computing. The
pizza-bakery example is replaced by Lagrange polynomials, generators become time step-
ping methods for ODEs, and so on.
Finally we have to mention the nearly infinite amount of literature on the web. The
web was also a big source of knowledge when preparing this book. Literature from the web
often covers things that are new, but can also be totally outdated. The web also presents
solutions and interpretations which might contradict each other. We strongly recommend
to use the web as additional source, but we consider a "traditional" textbook with the web
resources "edited" as the better entry point to a rich new world.
1.3 Installation and Configuration Instructions
Before diving into the subject of the book you should have all relevant tools installed on
your computer. We will give you some advice and recommend tools you might want. All
tools we name are public domain and free1
.
1.3.1 Installation
Python and all third-party packages (modules) we use in this book are free.
There are currently two major versions of Python; the 2.x branch and the new 3.x
branch. The former is the most supported in terms of libraries and contains all the sci-
entific tools we need. The last and final major 2.x release is Python 2.7 which is the one
we will use in this book. The 3.x branch contains many language improvements but still
lacks wide library support and is not backwards compatible with the 2.x branch. To learn
more about the difference, see [28].
For this book you need to install:
• the interpreter: Python 2.7
• the modules for scientific computing: SciPy with NumPy
• the module for graphical representation of mathematical results: matplotlib
• the shell: iPython
• (optional) a Python related editor, e.g., Spyder, Geany, Editra, DrPython
The installation of these depend on your operating system.
'Be aware that things might change; we try to collect updated information on the book's homepage
http://www.computingwithpython.com.
Chapter I Introduction
Ubuntu (Linux)
On Linux installation requires that you own administrator rights on your computer.
Ubuntu and most Linux distributions come with Python already installed. iPython, an
editor, matplotlib, SciPy can be installed using Ubuntu's package manager Synaptic. Fur-
thermore we recommend that you install the package installer python-pip. It provides
an easy way to install more modules, like
pip install assimulo
for installing a module for solving differential equations.
Windows
We recommend to download and install the distribution called python(x,y) from [29]. This
distribution is targeted for applications within scientific computing and comes with all
relevant modules like SciPy, matplotlib, NumPy. It also comes with the editor Spyder and
the IPython shell.
Mac OS X
Mac OS X comes with Python installed, just like most Linux systems. Later versions of
Mac OS X (10.6+) also come with NumPy.
A good alternative to install SciPy and matplotlib is to use the package system MacPorts
[19]. This will automatically install all dependencies needed and also contains many other
useful Python modules. The Scipy Superpack [31] is another good option that installs all
the necessary modules.
1.3.2 Configuration
Most Python code will, in this book and when you use it for real applications, be collected
in files. We recommend that you use the following header in all your Python files:
# -*- coding: UTF-8
from future import division
from scipy import *
from matplotlib.pyplot import *
This will
• allow you to use any non-ascii character, e.g., "a", "6" (assuming that you use the
UTF-8 encoding)
• activate a true division mode (1/2 will return 0.5 and not 0)
• import many standard modules and functions used in this book, e.g., SciPy.
Many editors, e.g. Spyder, provide the possibility to create a template for your files.
Look for this feature and put the above mentioned header into a template.
1.4 Executing Scripts
Python Shell
The Python shell is good but not optimal for interactive scripting. We therefore recom-
mend to use IPython instead [27].
1.4 Executing Scripts
iPython may be started in different ways, depending on your operating system.
• on Linux by running ipython --pylab in a shell
• on Windows by creating a shortcut, for which you choose the command
python.exe -c "import sys;
from IPython.ipapi import launch_new_instance;
sys.exit(launch_new_instance())"
• on Mac OS X by running ipython --pylab in Terminal
Executing Scripts
You often want to execute the contents of a file.
• Use the command cd in IPython in order to move to the directory where your file is
located
• To execute the contents of a file named f ile. py just run the command
execfile('file.py')
in the IPython shell.
Getting Help
Here are some tips on how to use IPython:
• To get help on an object just type ? after the object's name and then return
• Use the arrow keys to reuse the last executed commands
• You may use the tab key for completion (i.e., you write the first letter of a variable or
method, and IPython shows you a menu with all the possible completions)
• Use Ctrl+D to quit
• Use iPython's magic functions. You find a list and explanations by applying the func-
tion %itiagic at command prompt.
You can find out more about IPython from the online documentation [14].
CHAPTER II
Getting Started
In this chapter we will give a brief overview over the principal syntactical elements of
Python.
Readers who are starting to learn programing are guided through the book by this chap-
ter. Every topic presented here is in a "how-to" way and will be explained deeper later in
the book in a conceptual way and also enriched with many applications and extensions.
Readers who are already familiar with another programing language will find the Python
way of doing classical language constructs as a way to easily getting started with Python.
Both types of readers are encouraged to take this chapter as a brief guideline when
zigzagging through the book.
11.1 Program and Program Flow
A program is a sequence of statements which are executed in a top-down order. This linear
execution order has two important exceptions:
• There might be a conditional execution of alternative groups of statements (blocks),
which we refer to as branching,
• and there are blocks which are executed repetitively, which is called looping, see
Figure ILL
i
Condition
Linear
Figure 11.1 Program Flow
TV
Branching
Condition
Loop
Python uses a special syntax to mark blocks of statements: a keyword, a colon and an
indented sequence of statements, which belong to the block, see Figure II.2.
Comments
If a line in a program contains the symbol # everything following on the same line is
considered as a comment:
# This is a comment of the following statement
a - 3 # ... which might get a further comment here
11.2 Basic Types
Colon marks
the beginning
ofa block.
Indentation is
mandatory and shows
the extent of the block.
if a > b:
s = a/b
else :
s = 2*b-a The block ends when
the indentation returns
to the previous level.
Figure 11.2 Example of a block command
Line joining
A backslash () at the end of the line marks the next line as a continuation line, i.e.,
explicit line joining. If the line ends before all parentheses are closed the following line
will automatically be recognized as a continuation line, i.e., implicit line joining.
11.2 Basic Types
Let us go over the basic types that you will encounter in Python.
11.2.1 Numbers
A number may be an integer, a real number or a complex number. The usual operations are
• + and - addition and subtraction
• * and / multiplication and division
• ** power.
For example,
2** (2+2) # 16
lj**2 # -1
Note the use of the symbol j to denote the imaginary part of a complex number.
More on complex numbers can be found in § III.2.3.
11.2.2 Strings
Strings are sequences of characters, enclosed by simple or double quotes:
'valid string'
"string with double quotes"
"you shouldn't forget cornments"
'these are double quotes:
Chapter II Getting Started
You may also use triple quotes for strings including multiple lines:
"""This is
a long,
long string"""
11.2.3 Variables
A variable is a reference to an object. An object may have several references. One uses the
assignment operator = to assign a value to a variable:
x = [3, 4] # a list object is created
y = x # this object now has two labels: x and y
del x # we delete one of the labels
del y # both labels are removed: the object is deleted
The value of a variable can be displayed by the print command1
:
x - [3, 4] # a list object is created
print(x)
11.2.4 Lists
Lists are a very useful construction and one of the basic types in Python.
A Python list is an ordered list of objects enclosed by square brackets. One accesses
elements of a list using zero-based indexes inside square brackets:
LI = [5, 6]
Ll[0] # 5
LI[1] #6
Ll[2] # raises IndexError
L2 = ['a', 1, [3, 4]]
L2 [0] # 'a'
L2[2][0] # 3
L2[-l] # last element: [3,4]
L2[-2] # second to last: 1
Indexing of the elements starts at zero. One can put objects of any type inside a list,
even other lists.
Some basic list functions are:
• range (n) creates a list with n elements, starting with zero.
print(range(5)) # returns [0, 1, 2, 3, 4]
'In this book we use the print () command with parentheses which is standard in Python 3.x.
11.2 Basic Types
• len gives the length of a list.
lenfl'a', 1, 2, 34]) # returns 4
• append appends an element to a list.
L = [ 'a', 'b', 'C ]
L [ -1 ] # 'C
L.append('d')
L # L is now ['a', 'h', 'c', 'd']
L [-1] # '6'
Operations on Lists
• The operator + concatenates two lists:
LI = [1, 2]
L2 = [3, 4]
L = Ll + L2 # [1, 2, 3, 4]
• As one might expect, multiplying a list with an integer concatenates the list with itself
several times: n*L is equivalent to L + L H + L.
n times
L = [1, 2]
3 * L # [1, 2, 1, 2, 1, 2]
11.2.5 Boolean Expressions
A Boolean expression is an expression that may have the value True or False.
Some common operators that yield conditional expressions are:
==, equal
! =, not equal
<, <=, less than, less than or equal
>, >=, greater than, greater than or equal
One combines different Boolean values with or and and. The keyword not gives the log-
ical negation of the expression that follows.
Comparisons can be chained so that for example x < y < z is equivalent to x < y
and y < z. The difference is that y is only evaluated once in the first example. In both
cases z is not evaluated at all when the first condition, x < y, evaluates to False.
2 >= 4 # False
2 < 3 < 4 # True
2 < 3 and 3 < 2 # False
2 != 3 < 4 or False # True
2 <= 2 and 2 >= 2 # True
not 2 == 3 # True
not False or True and False # True!
Chapter II Getting Started
Note the precedence rules: <, >, <=, >=, ! = , == have higher precedence than not.
The operators and, or have lowest precedence.
11.3 Loops
Loops are used to repetitively execute a sequence of statements while changing a variable
from iteration to iteration. This variable is called index variable. It is successively assigned
to the elements of a list, see § X.l:
L = [1, 2, 10]
for s in L:
print(s * 2) # output: 2 4 20
The part to be repeated in the for loop has to be properly indented:
for elt in my_list;
do_something()
something_else{)
etc
print("loop finished") # outside the for block
11.3.1 Repeating a Task
One typical use of a for loop is to repeat a certain task a fixed number of times:
n = 30
for iteration in range(n):
do_something # this gets executed n times
II.3.2 break and else
The for statement has two important keywords: break and else.
break quits the for loop even if the list we are iterating is not exhausted.
for x in x_values:
if x > threshold:
break
print(x)
else checks whether the for loop was broken with the break keyword. If it was not
broken the block following the keyword else is executed.
for x in x_values:
if x > threshold:
break
else:
print("all the x are below the threshold")
11.5 Functions
11.4 Conditional Statements
This section covers how to use conditions for branching, breaking or otherwise controlling
your code.
A conditional statement delimits a block that will be executed if the condition is true.
An optional block, started with the keyword else will be executed if the condition is not
fulfilled, Figure II.2:
We demonstrate this by printing |x|, the absolute value of x:
x = ...
if x >= 0:
print(x)
else:
print(-x)
f X if X > 0
1 —x otherwise
Any object can be tested for truth value, for use in an if or while statement. The rules
for how the truth values are obtained are explained in § III.3.2.
11.5 Functions
Functions are useful to gather similar pieces of code in one place. Consider the following
mathematical function:
x f{x) := 2x + 1
The Python equivalent is:
def f(x):
return 2*x + 1
• the keyword def tells Python we are defining a function
• f is the name of the function
The start of the
function is indicated
by the keyword def
The function parameters
are comma separated.
I
def
/
addfargl, arg2)
s = argl + arg2
return s
The function
header ends with
a colon.
Indentation is not
optional and shows
what block belongs
to the function.
The return statement (optional)
specifies what is returned by the
function. If omitted, the function
returns None.
Figure 11.3 Anatomy of a function
Chapter II Getting Started
• x is the argument, or input of the function
• what is after return is called the output of the function
Once the function is defined it may now be called using:
f ( 2 ) # 5
f(l) # 3
• etc.
11.6 Scripts and Modules
A collection of statements in a file, (which usually has a py extension), is called a script.
Suppose that we put the contents of the following code into a file named smart script. py:
def f(x):
return 2*x + 1
z = []
for x in range(10):
if f(x) > pi:
z.append(x)
else:
z.append(-1)
print(z)
In a Python or iPython shell such a script can then be executed with a single command
execflie('sraartscript.py')
11.6.1 Simple Modules - Collecting Functions
Often one collects functions in a script. This creates a module with additional Python
functionality:
To demonstrate this we create a module by collecting functions in a single file, e.g.,
smartfunctions.py:
def f(x):
return 2*x + 1
def g(x):
return x**2 + 4*x 5
def h(x):
return l/f(x)
• These functions can now be used by any external script or directly in the IPython
environment.
• Functions within the module can depend on each other.
11.7 Interpreter
• Grouping functions with a common theme or purpose gives modules that can be
shared and used by others.
Again the command execfile(' smartfunctions .py') makes these functions avail-
able to your iPython shell2
. In Python terminology one says that they are put into the
actual namespace.
11.6.2 Using Modules and Namespaces
Alternatively, the modules can be imported by the command import. It creates a named
namespace. The command from puts the functions into the general namespace.
import smartfunctions
print(smartfunctions.f(2))
# 5
from smartfunctions import g fimport just this one function
print(g(1))
# 0
from smartfunctions import * #import all
print(h(2)*f(2))
# I
Note that the commands import and from import the functions only once into the re-
spective namespace. Changing the functions has no effect for the current Python session.
More on modules can be found in § XII.3.
11.7 Interpreter
The Python interpreter executes the following steps
1. First run for the syntax
2. Then execute the code line by line
3. Code inside a function or class declaration is not executed (but checked for syntax)
def f(x):
return y**2
a = 3
# here both a and f are defined
You can run the program above because there are no syntactical errors. You get an error
when you call the function f, though.
f(2) # error, y is not defined
2
Note that there is also the iPython magic function run
CHAPTER III
Variables and Basic Types
In this chapter we will present the most important and basic types in Python. What is a
type? It is a set consisting of data content, its representation and all possible operations.
Later in this book we will make this definition much more precise, when we introduce the
concepts of a class in Chapter IX.
111.1 Variables
Variables are references to Python objects. They are created by assignments:
a=l
diameter=3.
height=5.
cylinder=[diameter,height] # reference to a list
Variables take names which consist of any combination of capital and small letters, the
underscore (_), and digits. A variable name must not start with a digit. Note that variable
names are case sensitive.
A good naming of variables is an essential part of documenting your work, so we rec-
ommend to use descriptive variable names.
Python has some reserved keywords, which cannot be used as variable names, see
Table III.l. An attempt to do so would raise a syntax error.
Table 111.1 Reserved Python keywords
and as assert break class continue def del
eiif else except exec finally for from global
if import in is lambda not or pass
print raise return try while yield
As opposed to other programing languages, Python variables require no type
declaration.
One can create several variables with a multiple assignment statement:
a=:b = c = l#a, h and c get the same value 1
III.2 Numeric Types
Variables can be altered after their definition
a = 1
a = a + 1 # a gets the value 2
a = 3 * a ff a gets the value 6
The last two statements can be written combining the operation with an assignment
directly by using increment operators:
a += 1 # same as a - a + 1
a *= 3 # same as a = 3 * a
111.2 Numeric Types
At some point you will have to work with numbers, so we start by considering different
forms of numeric types in Python. In mathematics we distinguish between natural num-
bers (N), integers (Z), rational numbers (Q), real numbers (E) and complex numbers (C).
These are infinite sets of numbers. Operations differ between these sets and may not even
be defined. For example the usual division of two numbers in Z might not result in an
integer - it is not defined on Z.
In Python, like in many other computer languages, we have numeric types
• the numeric type int, which is a finite subset of Z,
• the numeric type float, which is a finite subset of E and
• the numeric type complex, which is a finite subset of C.
As these are finite sets, there is a smallest and a largest number and there is a smallest
spacing between numbers, see § III.2.2.
111.2.1 integers
The simplest numerical type is the integer type.
Plain Integers
The statement k = 3 assigns the variable k to an integer.
Applying an operation of the type +, -, * to integers returns an integer.
Caution: Division in Python
The behavior of the division operator with integers is very unintuitive. Compare the fol-
lowing expressions:
1/2 # gives the result 0!
1.0/2.0 # gives the result 0.5
In order to obviate this potential pitfall, we strongly advise to start each and every Python
file by the following line:
from future import division
This will activate the true division inside the corresponding file, i.e., the expression 1/2
now returns 0.5. Note that the integer division remains available through the operator //.
Chapter III Variables and Basic Types
Py3k: True Division is on by Default
As this behavior of the division is error-prone it is changed in Python 3. The default division
is the true division, i.e., 1/2 always returns 0.5.
The set of integers in Python is bounded: {(-2)31
,..., -1, 0, 1,... 231
- 1). To represent
a plain integer 32 bits are used (31 for the number and 1 for the sign).
The maximal integer is accessible in the Python variable sys.maxint (after first im-
porting the module sys, see § XII.3).
Long Integers
What happens when a calculation results in a number which exceeds the maximal repre-
sentable integer?
»> 2**31
21474836481.
The result is of another type. It is a long integer. Long integers are displayed by their digits
appended by the letter "L".
Operations with long integers result in long integers
k = 2**31-1
type(k) # returns: <type 'long'>
k = int(k) # performs a type conversion to plain integer
The expression int(k) converts a number k to a plain integer if k is in the range of
plain integers. Otherwise the result is a long integer. The expression long(k) converts k
to a long integer.
In scientific computing integers are mostly used as counters and long integers are rarely
used. In contrast, computations in number theory often require to represent numbers in
the unbounded set of long integers.
Caution: Performance of Long integers
Note that computations with long integers may be significantly slower than with plain
integers.
Py3k: No distinction integer/long integer
In Python 3, there is no distinction between standard and long integers anymore.
111.2.2 Floating Point Numbers
Floating Point Representation
If you execute the statement a = 3.0 in Python, you create a floating point number
(Python type float). These numbers form a subset of the rational numbers, Q.
III.2 Numeric Types
Alternatively the constant could have been given in exponent notation a = 30. Oe-l
or simply a = 30 . e-1. The symbol e separates the exponent from the mantissa and the
expression reads in mathematical notation a — 30.0 x 10_1
.
The name floating point number refers to the internal representation of these numbers
and reflects the floating position of the decimal point when considering numbers over a
wide range.
Applying the elementary mathematical operations +, *, / to two floating point num-
bers or to an integer and a floating point number returns a floating point number.
Operations between floating point numbers rarely return the exact result expected from
rational number operations:
0.4 - 0.3 # returns 0.10000000000000003
This facts matters, when comparing floating point numbers:
0.4 - 0.3 == 0.1 # returns False
see § XIV.2.6.
Internally, floating point numbers are represented by four quantities: the sign, the man-
tissa, the exponent sign and the exponent:
sign(x) (xq + + • • • +
with fi eN and Xq # 0, 0 < x,- < p.
X().. .xt_] is called the mantissa, p the basis and e the exponent e < U. t is called the
mantissa length.
The condition xq # 0 makes the representation unique and saves in the binary case
{P = 2) one bit.
There exist two floating point zeros +0 and -0, both represented by the mantissa
being 0.
On a typical Intel processor p = 2. To represent a number in the Python type float
64 bits are used, namely 2 bits for the signs, t = 52 bits for the mantissa and 10 bits for
the exponent e.
With this data the smallest positive representable number is
flmin = 1. 2-1023
% IQ-308
and the largest is
flmax = 1.111... 1 x 21023
^ 10308
.
Note that floating point numbers are not equally spaced in [0, flmax]. There is in particular
a 'huge' gap at zero [32, p. 11]: The distance between 0 and the first positive number is
2-1023
, while the distance between the first and the second is smaller by a factor 2_52
«
2.2 x 10"16
, cf. Figure III.l. This effect is caused by the normalization xq # 0.
This gap is filled equidistantly with subnormal floating point numbers to which such a
result is rounded. Subnormal floating point numbers have the smallest possible exponent
and do not follow the convention that the leading digit xq has to differ from zero, [12].
0.0 1.0 2.0
I H-H—^—I—^—I
Figure 111.1 The floating point gap at zero. Here f = 3, L/ = 1.
Chapter III Variables and Basic Types
Infinite and Not a Number
There are in total 2(^ - l)^f_1
(2[/ + 1) + 1 floating point numbers.
Sometimes a numerical algorithm computes numbers outside this range. This generates
number over- or underflow. In SciPy a special floating point number inf is assigned to
overflow results:
>» exp 1000.)
inf
»> a - inf
»> 3 - a
-inf
»> 3 + a
inf
Working with inf may lead to mathematically undefined results. This is indicated in
Python by assigning the result a special floating point number: nan. This stands for not-
a-number, i.e., an undefined result of a mathematical operation:
>>> a+a
inf
»> a-a
nan
A
A
A
a/a
nan
There are special rules for operations with nan and inf. For instance, nan compared to
anything (even to itself) always returns False:
x = nan
x < 0 # False
x > 0 # False
x == x # False
See Exercise 4 for some surprising consequences of the fact that nan is never equal to itself.
The float inf behaves much more as expected:
infinity - inf
0 < infinity # True
infinity <= infinity # True
infinity -- infinity # True
-infinity < infinity # True
infinity - infinity # nan
A way to check for nan and inf is to use the functions isnan and isinf.
Often, one wants to react directly, when a variable gets the value nan or inf. This can
be achieved by using the NumPy command seterr. The command sequence
seterr(all='raise' )
raises an error, if a calculation would return one of those values.
III.2 Numeric Types
Underflow: Machine Epsilon
Underflow occurs, when an operation results in a rational number which falls into the
"gap at zero", see Figure III.l.
Definition: Machine Epsilon
The machine epsilon or rounding unit is the largest number e such that
float(1.0 + £) = 1.0
Notethate ^ ^1_t
/2 = 1.1102xl0_16
on most of todays computers. The value which is
valid on the actual machine you are running your code on is accessible via the command
import sys
sys.float_info.epsilon # 2.220446049250313e-16 (depending on
your system)
If you execute sys. floatJLnfo you get more information about the internal repre-
sentation of the float type on your machine.
The function float converts other types to a floating point number - if possible.
This function is especially useful when converting an appropriate string to a number
a = float('1.356').
Other float types in NumPy
NumPy also provides other float types, known from other programing languages as single
and double precision numbers, namely float64 and float32:
a = pi # returns 3.141592653589793
al = float64(a) # returns 3.1415926535897931
a2=float32(a) # returns 3.1415927
a - al # returns 0.0
a - a2 # returns -8. 7422780126189537e-08
The second last line demonstrates that a and al do not differ in accuracy. In the first
two lines they only differ in the way they are displayed. The real difference in accuracy is
between a and its single precision counterpart a2.
The NumPy function f info can be used to display information on these floating point
types:
f32 = finfo(float32)
f32.precision # 6 (decimal digits)
f64 = finfo(float64)
f64.precision # 15 (decimal digits)
f = finfo(float)
f.precision # 15 (decimal digits)
f64.max # 1. 7976931348623157e+308 (largest number)
f32.max # 3.4028235e+38 (largest number)
help(finfo) # Check for more options
Chapter III Variables and Basic Types
111.2.3 Complex Numbers
Complex numbers are an extension of the real numbers frequently used in many scientific
and engineering fields.
Complex Numbers in Mathematics
Complex numbers consist of two floating point numbers, the real part a of the number
and its imaginary part b. In mathematics a complex number is written as
2 = « + M,
where i defined by i2
= -1 is the imaginary unit. The conjugate complex counterpart of
z is
z — a — bi.
If the real part a is zero the number is called an imaginary number.
The j Notation
In Python imaginary numbers are characterized by suffixing a floating point number with
the letter j, e.g. z = 5.2j. A complex number is formed by the sum of a floating point
number and an imaginary number, e.g., z=3.5+5.2 j.
While in mathematics the imaginary part is expressed as a product of a real number
b with the imaginary unit i, the Python way of expressing an imaginary number is not a
product: j is just a suffix to indicate that the number is imaginary.
This is demonstrated by the following small experiment:
b=5 .2
z=bj # returns a (name) error
z=b*j # returns a (name) error
z=b*lj # is correct
The method conjugate returns the conjugate of z:
z=3.2+5.2j
z.conjugate() # returns (3.2-5.2j)
Real and Imaginary Parts
One may access the real and imaginary parts of a complex z using the attributes real and
imag. Those attributes are read-only:
z — 1 j
z.real # 0
z.imag # 1
z.imag — 2 # error
Note also that it is not possible to convert a complex number to a real number:
z = 1 + Oj
z == 1 # True
float(z) # error
III.3 Booleans
Interestingly, the attributes real and imag, as well as the method conjugate work
just as well for complex arrays (see Chapter V). We demonstrate this by computing the ]Vth
roots of unity which are z/< = ei27tk
/N
i k = 0,..., N - 1, i.e., the N solutions of zN
= 1:
N = 10
# the following vector contains the Nth roots of unity:
unity_roots = array([exp(Ij*2*pi*k/N) for k in range(N)])
# access all the real or imaginary parts with real or imag:
plot(unity_roots.real, unity_roots.imag, 'o')
allclose(unity_roots**N, 1) # True
It is of course possible to mix the previous methods, as illustrated by the following
examples:
z=3.2+5.2j
(z+z.conjugate())/2. # returns (3.2+0j)
((z+z.conjugate())/2.) .real # returns 3.2
(z-z.conjugate())/2. # returns 5.2j
((z-z.conj ugate())/2.) .imag # returns 5.2
sqrt(z*z.conjugate()) # returns (6.1057350089894991+0j)
111.3 Booleans
A Boolean1
variable can take only two values, True and False.
The main use of this type is in logical expressions. Here are some examples:
a = True
b = 30>45 # b gets the value False
Boolean expressions are often used in conjunction with the if statement.
if x>0:
print "positive")
else:
print "nonpositive")
Earned after George Boole (1815-1864).
Chapter III Variables and Basic Types
Caution: True and False are variables
Note that in Python, True and False are merely variables and not reserved keywords
(Table 111.1). It means that you may technically redefine those variables as in
True = 2
Of course, you should never do that, even if Python allows it, because it will render your
code completely unreadable. (To recover, you might simply execute True = 1 > 0, and
False = not True.)
111.3.1 Boolean Operators: and, or, not
The Boolean operations are performed using the keywords and, or and not in Python.
True and False # False
False or True # True
(30 > 45) or (27 < 30) # True
not True # False
not (3 > 4) # True
The operators follow some precedence rules, see § II.2.5, which would make the paren-
theses in the third line and in the last obsolete. It is a good practice to use them anyway
to increase the readability of your code.
Note that the operator and is implicitly chained in the following Boolean expressions:
a < b < c # same as: a < b and b < c
a == b == c # same as: a == b and b == c
iil.3.2 Boolean Casting
Most objects in Python may be converted to Booleans, this is called Boolean casting. The
built-in function bool performs that conversion. Note that most objects are cast to True,
except zero, the empty tuple, the empty list, the empty string or the empty array. These
are cast to False.
It is not possible to cast arrays into Booleans, unless they contain no or one element; this
is explained further in § VI.2.1. The rules for Boolean casting are summarized in Table III.2.
Table 111.2 Rules of conversion to Boolean.
bool False True
string / / 'not empty'
number 0 /o
list [] t.. . ] (not empty)
tuple () (..,..) (not empty)
array array([]) array ( [a] ) (a ^ 0)
array array([0,0])
array Exception raised if array contains more than one element
III.3 Booleans
Some usage examples:
bool([]) # False
bool(O) # False
bool(' ') # True
bool('') # False
bool('hello') # True
bool(1.2) # True
bool(array([1])) # True
bool(array([1,2])) # Exception raised!
Automatic Boolean Casting
Using an if statement with a non-Boolean type will cast it to a Boolean. In other words,
the following two statements are always equivalent:
if a:
if bool(a): # exactly the same as above
A typical example is a test if a list is empty:
# L is a list
if L:
print("list not empty")
else:
print("list i s empty")
An empty array, list or tuple will return False.
You can also use a variable in the if statement, for example an integer:
# n is an integer
if n % 2:
print("n is odd")
else:
print("n is even")
Note that we used % for the modulo operation, which returns the remainder of an integer
division. In this case, it returns 0 or 1 as the remainder after modulo 2.
In this last example, the values 0 or 1 are cast to bool, see § III.3.4.
Boolean operators (or, and, not) will also implicitly convert some of their arguments
to a Boolean.
111.3.3 Return values of and and or
Note that the operators and and or do not necessarily produce Boolean values.
Chapter III Variables and Basic Types
The expression x and y is equivalent to
def and_as_function(x,y):
if not x:
return x
else:
return y
and the expression x or y is equivalent to
def or_as_function(x,y):
if x:
return x
else:
return y
Interestingly, this means that when executing the statement True or x, the variable x
need not even to be defined! The same holds for False and x.
Note that, unlike their counterparts in mathematical logics, these operators are no
longer commutative in Python. Indeed, the following expressions are not equivalent:
[1] or 'a' # produces [1]
'a' or [1] # produces 'a'
111.3.4 Booleans and Integers
In fact, Booleans and integers are the same. The only difference is in the string represen-
tation of 0 and 1 which is in the case of Booleans 'False' and 'True' respectively.
This allows constructions like this:
def print_ispositive(x):
possibilities=['nonpositive', 'positive']
return "x is {}".format(possibilities[x>0]) #(for the format
method see § III.4.2)
We note for the readers already familiar with the concept of subclasses, that the type
bool is a subclass of the type int, cf., § IX.3. Indeed all four inquiries isinstance (True,
bool), isinstance(False, bool), isinstance(True, int), and isinstance
(False, int) return the value True, see § IV.7.
Even rarely used statements like True+13 are syntactically correct.
111.4 Strings
The type string is a type used for text:
name = 'Johan Carlsson'
child = "Anna is Johan Carlsson's daughter"
book = " " "Aunt Julia
and the Scriptwriter" " "
III.4 Strings 25
A string is enclosed either by single or double quotes. If a string contains several lines it
has to be enclosed by three double quotes "" or three single quotes ''
Strings can be indexed with simple indexes or slices (see § IV. 1.1 for a comprehensive
explanation on slices.)
book[-l] # returns 'r'
book[-12:] # returns 'Scriptwriter'
Strings are like tuples immutable, i.e., items cannot be altered. The command
book [ 1 ] =' a' returns
TypeError: 'str' object does not support item assignment
The string 'n' is used to insert a line break (LF linefeed) and 't' inserts a horizontal
tabulator (TAB) into the string to align several lines
print('Temperature: t20tCnPressure:t5tPa')
These strings are examples of escape sequences. Escape sequences always start with a
backslash ''.
A multiline string automatically includes escape sequences:
a=
A multiline
example" " "
a # returns 'nA multilinenexample'
111.4.1 Operations on strings and string methods
Addition of strings performs concatenation:
last_name='Carlsson'
f irst_name='Johanna'
Full_name=first_name+' '+last_name # returns 'Carlsson Johanna'
Multiplication is just repeated addition:
game=2*'Yo' it returns 'YoYo'
When strings are compared, lexicographical order applies and the upper-case form precedes
the lower-case form of the same letter:
'Anna' > 'Arvid' # returns false
'ANNA' < 'anna' # returns true
'10B' < '11A'# returns true
Chapter III Variables and Basic Types
Among the variety of string methods we mention here only the most important ones:
• Splitting a string: The split method generates a list from a string by using a single
or multiple blank as a separator. Alternatively an argument can be given specifying a
particular string as a separator:
text='quod erat demonstrandum'
text.split() # returns ['quod', 'erat', 'demonstrandum']
table='Johan;Carlsson;19890327'
table.split(';') # returns ['Johan','Carlsson','19890327']
king='CarlXVIGustaf'
king.split('XVI') # returns ['Carl', 'Gustaf']
• Joining a list to a string: this is the reverse operation to split
sep=';'
sep.join(['Johan','Carlsson','19890327']) # returns 'Johan;
Carlsson;19890327'
• Searching in a string: The find method returns the first index in the string, where a
given search string starts. If the search string is not found -1 is returned:
birthday^'20101210'
birthday.find('10') # returns 2
111.4.2 String Formatting
String formatting is done using the format method:
course_code = "NUMA21"
print("This course's name is {}".format(course_code))
# This course's name is NUMA21
The function format is a string method, which scans the string for the occurrence of
placeholders, which are enclosed by curly brackets. These placeholders are replaced in a
way specified by the argument of the format method. How they are replaced depends on
the format specification defined in each {} pair. Format specifications are indicated by a
colon as their prefix.
The format method offers a range of possibilities to customize the formatting of objects
depending on their types. Of particular use in scientific computing are the formatting
options for the float type. One may choose either the standard fixed point notation with
{: f}, or the exponential notation with {: e}:
quantity - 33.45
print ("{:f}".format(quantity)) # 33.450000
print("{:1.If} format(quantity)) #33.5
print ("{:.2e}".format(quantity)) # 3.35e+01
111.5 Exercises
In this example the name of the object which gets its value inserted is given as argument
to the format method. The first {} pair is replaced by the first argument, the following pairs
by the subsequent arguments.
Alternatively, it may also be convenient to use the key-value syntax instead:
print("{name} {value:.If}".format(name="quantity",value=
quantity)) # "quantity 33.5"
Here, two values are processed, a string name without a format specifier and a float
value which is printed in fixed point notation with one digit after the decimal point.
Remark: Braces in the string
Sometimes a string might contain a pair of curly braces, which should not be considered
as placeholders for a format method. In that case double braces are used:
"we {} in LaTeX begin{{equation}}format('like' )
This returns the string 'we like in LaTeX begin{equation}'
We refer to the complete reference documentation for more details on string format-
ting, [37].
111.5 Exercises
Exercise 1. Check whether x = 2.3 is a zero of the function:
fix) = x2
+ 0.25x - 5
Exercise 2. According to de Moivre's formula, the following holds:
(cos x + i sin x)" = cos nx + i sin nx « e Z, x e R.
Choose numbers n and x and verify that formula in Python.
Exercise 3. Verify in the same way Euler's formula:
e'-* = cosx + isinx x € K.
Exercise 4. Suppose that we are trying to check the convergence of a diverging sequence (here the
sequence is defined by the recursion relation »„+1 = 2un and uq = 1.0):
u=1.0 # you have to use a float here!
uold=10.
for iteration in xrange(2000):
if not abs(u-uold) > l.e-8:
print('Convergence')
break # sequence has converged
uold=u
u=2*u
else:
print('No convergence')
Chapter III Variables and Basic Types
(a) Since the sequence does not converge, the code should print the "No convergence" message.
Execute it to see what happens.
(b) What happens if you replace the line
if not abs(u-uold) > l.e-8
if abs(u-uold) < l.e-8
It should give exactly the same result, shouldn't it? Run the code again to see what happens.
(c) What happens if you replace u = 1. by u = 1 (without decimal point). Run the code to check
your predictions.
(d) Explain the unexpected behavior of this code. The key to understand what happens is that
inf - inf evaluates to nan, and the comparison of nan with anything is always False.
Exercise 5. An implication C = (A =?• B) is a Boolean expression which is defined as
• C is True if A is False or A and B are both True,
• C is False otherwise.
Write a Python function implication (a, b).
Exercise 6. This exercise is to train Boolean operations. Two binary digits (bits) are added by using a
logical device called a halfadder. It produces a carry bit (the digit of next higher value) and the sum
as defined by Table III.3, see also Figure III.2. A full adder consists of two half adders and sums up two
bits and an additional carry bit on the input, see Figure III.3.
by
Table 111.3 Definition of the
half-adder operation
p q sum carry
1
1
0
0
1
0
1
0
0
1
1
0
1
0
0
0
p
sum
q
carry
Figure 111.2 A half adder circuit
111.5 Exercises
carry in
A
B
HALF
ADDER
sum
carry out
HALF
ADDER
sum
carry out
OR
carry in sum
A FULL
ADDER
B carry out
Figure 111.3 A full adder circuit
Write a function which implements a half adder and another which implements a full adder. Test
these functions.
CHAPTER IV
Container Types
Container types are used to group objects together. The main difference between the dif-
ferent container types is the way the individual elements are accessed and how operations
are defined.
IV. 1 Lists
A list is, as the name hints, a list of objects of any kind.
L = 'a', 20.0, 5 J
M = [3,['a', -3.0, 5]]
The individual objects are enumerated by assigning each element an index. The first
element in the list gets the index 0. This zero-based indexing is frequently used in mathe-
matical notation1
.
The index allows access to these objects
L[1] # returns 20.0
L[0] # returns 'a'
M [ 1 ] # returns ['a',-3.0,5]
M[l][2] # returns 5
The bracket notation here corresponds to the use of subscripts in mathematical formulas.
l is a simple list, while m itself contains a list, so that one needs two indexes to access
an element of the inner list.
A list containing subsequent integers can be easily generated by the command range:
L=range(4) # generates a list with four elements: [0, 1, 2 ,3]
A more general use is to provide this command with start, stop and stride parameters
L=range(17,29,4) # generates [17, 21, 25]
'Consider the usual indexing of coefficients of a polynomial.
IV.1 Lists 31
The command len returns the length of the list
len(L) # returns 3
IV.1.1 Slicing
Slicing a list between i and / creates a new list containing the element starting at index /
and ending just before j.
For slicing a range of indexes has to be given: The l [ i: j ] means: create a list by taking
all elements from L starting at L [i] until L [ j -1]. In other words the new list is obtained
by removing the first i elements from L and taking the next j - i elements (for j > i > 0).
See Figure IV. 1 for more examples.
L = ['C, '1', 'o', 'u', 'd','s']
L[l:5] # remove one element and take three from there:
# returns I'l', 'o', 'uV'd'J
L[2:5] 0 1 2 3 4 5 -1
L[2:] 0 1 2 3 -3 -2 -1
L [: 2] 0 1 2 3 -3 -2
L[2:-l] 0 1 2 3 -3 -2 -1
L [-4:-1] 0 1 -5 -4 -3 -2
L[:-2] 0 1 2 3 -3 -2 -1
L[-2:] 0 1 2 3 -3
Li J
Figure IV.1 Some typical slicing situations. Note the syntax: l [i: ] means "remove the / first
elements", l [: i] means "take only the first / elements", and, similarly, l [: - i] means
"remove the last / elements" and l [-i: ] means "take only the last; elements". This may be
combined in L[i: -j ], to remove the first / and the last j elements.
Chapter IV Container Types
One may omit the first or last bound of the slicing:
L = ['C, '1', 'o', 'u','d', 's']
L[l:] # ['1', 'o', 'u', 'd','s']
L [ : 5 ] # ['C , '1 ', 'o', 'W , 'd ' ]
L[:] # the entire list
Python allows the use of negative indexes for counting from the right. In particular,
the element l [ -1 ] is the last element in the list l.
• l [ - i; ] amounts to take the last i elements
• l [: - i] amounts to take all elements except the / last ones
Here is an example:
L = ['C, '1', 'o', 'u','d', 's']
L [-2 : ] # ['d', 's']
L [ : -2 ] # ['C , '1 ', 'o', ' u ' ]
Mathematical Analogy: Half-Intervals
Omitting one index in the range corresponds to half lines in R. The half-open interval
(-oo, a) means: take all numbers strictly lower than a; this is similar to the syntax l [: j ].
Remark: Out of bound slices
Take notice that you never get index errors with out of bound slices. Possibly, you may
obtain empty lists.
L = range (4) # [0, 1, 2, 3]
L[4] # error!
L [1:100] # same as L[1:]
L[-100:-l] # same as L[:-l]
L[-100:100] # same as L[:]
L[5:0] # empty
L [-2 : 2] # empty
Caution: Variable indexing that becomes negative
Be careful when using variables in indexing that may become negative, since it changes
the slice completely. This might lead to unexpected results:
a = [1,2,3]
for iteration in range(4):
print(sum(a[0:iteration-1]))
The result is 3, 0,1, 3 while one expects 0,0,1,3.
IV.1 Lists
Strides
When computing slices one may also specify a stride which is the length of the step from
one index to the other. The default stride is one.
L = range(100)
L[:10:2] # [0, 2, 4, 6, 8]
L [ : : 20] # [0, 20, 40, 60, 80]
L [ 10 : 20 : 3 ] # [10, 13, 16, 19]
Note that the stride may also be negative:
L [20 :10 : -3 ] # [20, 17, 14, 11
It is also possible to create a new list which is reversed, using a negative stride:
L = [1, 2, 3]
R = L[::-1] # L is not modified
R # [3, 2, 1]
see also reverse in § IV. 1.4.
IV.1.2 Altering lists
Typical operations on lists are insertion and deletion of elements and list concatenation.
With the slicing notation, list insertion and deletion becomes obvious: Deletion is just
replacing a part of a list by an empty list [ ]:
L = ['a', 1, 2, 3, 4]
L 2:3] = [] # ['a', 1, 3, 4]
L 3:] = [ # ['a', 1, 3]
Insertion is replacing an empty slice by the list to be inserted:
L [ 1:1] = [1000, 2000] # ['a', 1000, 2000, 1, 3]
Two lists are concatenated by the "plus" operator:
L = [1, -17]
M = [-23.5, 18.3, 5.0]
L+M # gives [1, -17, 23.5, 18.3, 5.0]
Concatenating a list n times with itself motivates the use of the "multiplication"
operator:
n = 3
n* [1.,17,3] # gives [1. , 17, 3, 1., 17, 3, 1., 17, 3]
[ 0 ] * 5 # gi ves [0,0,0,0,0]
There exist no arithmetic operations on lists, like element-wise summation or division.
For this we refer to arrays, see § IV.2.
Chapter IV Container Types
IV.1.3 Belonging to a list
One may use the keywords in and not in to determine whether an element belongs to
a list (similar to e and ^ in mathematics):
L = ['a', 1, 'b'( 2]
'a' in L # True
3 in L # False
4 not in L # True
IV. 1.4 List Methods
Some useful methods of the list type are collected in Table IV.l.
Table IV.1 Methods of the type list.
command action
list.append(x)
list.expand(L)
list.insert(i,x)
list.remove(x)
list.count(x)
list.sort()
list.reverse()
list.pop()
add x to the end of the list.
expands the list by the elements of the list l.
insert x at position i.
remove the first item from the list whose value is x.
the number of times x appears in the list,
sort the items of the list, in place,
reverse the elements of the list, in place,
removes the last element of the list, in place.
There are two ways list methods can act:
• they can directly alter the list, i.e. in-place operation
• they produce a new object
In-place operations
All methods which result in a list are in-place operating methods, e.g. the method
reverse:
L = [1, 2, 3]
L.reverse!) # the list L is now reversed
L # [3, 2, 1]
Caution: Be aware of in-place operations
One might be tempted to write
L=[3, 4, 4, 5]
newL = L.sort()
This is correct Python. But it results in a (perhaps) unintended alternation of l and a
variable newL having the value None. The reason is that sort operates in-place.
IV.1 Lists
Here we demonstrate in-place operating methods:
L = [0,1,2 ,3 ,4 ]
L.append(5) # [0, 1, 2, 3, 4, 5]
L.reverse() # [5, 4, 3, 2, 1, 0]
L.sort() # [C , , 2, 3, 4, 5]
L.remove(0) # [1, 2, 3, 4, 5]
L.pop() [1 / 2, 3, 4]
L.pop() [1 / 2, 3]
L.extend([' a' /
/ b' , ' c' ] ) [1 , 2, 3, 'a', 'b', 'c']
L is altered.
The method count is an example of a method which generates a new object:
L.count(2) # returns 1
IV.1.5 Merging Lists - zip
A particularly useful function for lists is zip. It merges two given lists into a new list by
pairing the elements of the original lists. The result is a list of tuples, see § IV.3:
ind = [0,1,2,3,4]
color = ["red", "green", "blue", "alpha"]
zip(color,ind) # gives [('red', 0), ('green', 1), ('blue', 2),
('alpha', 3)]
This example also demonstrates what happens if the lists have different lengths. The
length of the zipped list is the shorter length of the two input lists.
IV.1.6 List Comprehension
A convenient way to build up lists is to use the list comprehension construct, possibly with
a condition inside.
The syntax of a list comprehension is
[<expr> for <variable> in <list>]
or more general
[<expr> for <variable> in <list> if <condition>]
Example IV.1
L = [2, 3, 10, 1, 5]
L2 = [x*2 for x in L] # [4, 6, 20, 2, 10]
L3 = [x*2 for x in L if 4 < x <= 10] # [20, 10]
Chapter IV Container Types
It is possible to have several for loops inside a list comprehension:
M=[[1,2,3], [4,5,6]]
flat - [M[i][j] for i in range(2) for j in range(3)] # [1, 2, 3,
4, 5, 6]
This is of particular interest when dealing with arrays, see § IV.2.
Remark: The map built-in function
It is also possible to use the map function to achieve the same effect. The following two
pieces of code produce the same outcome:
L = [1,2,3]
[x*2 for x in L] # [2,4,6]
map(lambda x: x*2, L) # [2,4,6]
Note however that the use of map forces one to define a function (here an anonymous
function, see § VIII.7). Arguably, the list comprehension version is more readable. Since
the map version has no advantage over the list comprehension approach, it is rarely useful.
Mathematical Analogy: Set Notation
List comprehension is closely related to the mathematical notation for sets. Compare:
L2 = {2x; x e L]
and
L2 = [2*x for x in L]
One big difference, though, is that lists are ordered while sets aren't, see § IV.5.
IV.2 Arrays
The NumPy package offers arrays, which are container structures for manipulating vectors,
matrices or even higher order tensors in mathematics. In this section we point out the
similarities of arrays and lists. But arrays deserve a broader presentation, which will be
given in in Chapter V and Chapter VI.
Arrays are constructed from lists by the function array:
v = array([l.,2.,3.])
A = array([[l.,2.,3.],[4.,5.,6.]])
To access an element of a vector we need one index, while an element of a matrix is
addressed by two indexes
v [2 ] # returns 3.0
A [ 1, 2 ] # returns 6.0
IV.3 Tuples
At a first glance, arrays are similar to lists, but be aware they are different in a funda-
mental way:
• Access to array data corresponds to that of lists, using square brackets and slices, see
§ IV.l. They may also be used to alter the array:
M = array([[1.,2.],[3.,4.]])
v = array([!., 2., 3.])
v[0] # 1.
v[:2] # array ( [1., 2. ])
M[0,1] # 2.
v[:2] = [10, 201 # v is now array([10., 20., 3.])
• the number of elements in a vector, or the number of rows of a matrix is obtained by
the function len:
len(v) # 3
• Arrays store only elements of the same numeric type (usually float or complex but
also int), see § V.3.1
• The operations +, *, /, - are all elementwise. dot is used for the scalar product and the
corresponding matrix operations.
• Unlike lists, there is no append method for arrays. Nevertheless there are special meth-
ods to construct arrays by stacking smaller size arrays, see § V.7. A related point is that
arrays are not "elastic" as lists: one cannot use slices to change their length.
• Vector slices are views, i.e., they may be used to modify the original array, see § VI.l.
IV.3 Tuples
A tuple is an immutable list. Immutable means that it cannot be modified. A tuple is just a
comma separated sequence of objects (a list without brackets). To increase readability one
often encloses a tuple in a pair of parentheses:
my_tuple =1, 2, 3 # our first tuple
my_tuple = (1, 2, 3) # the same
my_tuple =1, 2, 3, # again the same
len(my_tuple) # 3, same as for lists
iny_tuple[0] = 'a' # error! tuples are immutable
The comma indicates that the object is a tuple:
singleton =1, # note the comma
len(singleton) # 1
Chapter IV Container Types
Tuples are useful when a group of values go together, for example, they are used to
return multiple values from functions § VIII.3.
One may assign several variables at once by unpacking a list or tuple:
a, b = 0, 1 # a gets 0 and b gets 1
a, b = [0, 1] # exactly the same effect
(a, b) = 0, 1 # same
[a,b] = [0,1] # same thing
Remark: The swapping trick
Use packing and unpacking to swap the contents of two variables:
a, b = b, a
To summarize:
• Tuples are nothing else than immutable lists with a notation without brackets
• In most cases lists may be used instead of tuples
• The notation without parenthesis is convenient but dangerous. You should use paren-
theses when you are not sure:
a, b = b, a # the swap trick; equivalent to:
(a, b) = (b, a)
# but
1, 2 == 3, 4 # returns (1, False, 4)
(1, 2) == (3, 4) # returns False
IV.4 Dictionaries
Lists, tuples and arrays are ordered sets of objects. The individual objects are inserted,
accessed and processed according to their place in the list. On the other hand, dictionaries
are unordered sets of pairs. One accesses dictionary data by keys.
IV.4.1 Creating and Altering Dictionaries
For example, we may create a dictionary containing the data of a rigid body in mechanics
as follows:
truck_wheel - {'name':'wheel' , 'mass':5.7 ,
'Ix' : 2 0 . 0, 'ly':1.,'Iz':17.,
'center of mass': [0 . ,0 . ,0.]}
IV.4 Dictionaries
Individual elements are accessed by their keys:
truck_wheel['name'] # returns 'wheel'
truck_wheel['mass'] # returns 5.7
and new objects are added to the dictionary by creating a new key:
truck_wheel['Ixy'] = 0.0
Dictionaries are also used to provide parameters to a function, see § VIII.2.
Keys in a dictionary can be among others: strings, functions, tuples with immutable
elements, and classes. Keys cannot be lists or arrays.
The command diet generates a dictionary from a list with key/value pairs:
truck_wheel = diet([('name','wheel'),('mass',5.7),('Ix',20.0),
('ly',1.), ('Iz',17.), ('center of
mass[0.,0.,0.])])
The function zip may come in handy in this context, see § IV. 1.5.
IV.4.2 Looping over Dictionaries
There are mainly three ways to loop over dictionaries:
• by keys:
for key in truck_wheel.keys():
print(key) # prints (in any order) 'Ix', ' ly', 'name',...
or equivalently,
for key in truck_wheel:
print (key) # prints (in any order) 'Ix', 'ly', 'name',...
• by value
for value in truck_wheel.value():
print (value) # prints (in any order) 1.0, 20.0, 17.0,
'wheel', ...
• by item, i.e., key/value pairs
for item in truck_wheel.items():
print (item) # prints (in any order) ('ly', 1.0), ('Ix',
20.0), ('Iz', 17.0), ('name', 'wheel'),
See § XIII.4 for a special dictionary object for file access.
Exploring the Variety of Random
Documents with Different Content
Computing With Python An Introduction To Python For Science Engineering Claus Fuher
Computing With Python An Introduction To Python For Science Engineering Claus Fuher
Computing With Python An Introduction To Python For Science Engineering Claus Fuher
The Project Gutenberg eBook of The
Philippines: Past and Present (Volume 2
of 2)
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Title: The Philippines: Past and Present (Volume 2 of 2)
Author: Dean C. Worcester
Release date: January 26, 2013 [eBook #41918]
Most recently updated: October 23, 2024
Language: English
Credits: Produced by Jeroen Hellingman and the Online
Distributed
Proofreading Team at http://www.pgdp.net/ for Project
Gutenberg (This book was produced from scanned
images of
public domain material from the Google Print project.)
*** START OF THE PROJECT GUTENBERG EBOOK THE
PHILIPPINES: PAST AND PRESENT (VOLUME 2 OF 2) ***
The Philippines Past and Present
THE MACMILLAN COMPANY
NEW YORK · BOSTON · CHICAGO · DALLAS ATLANTA · SAN
FRANCISCO
MACMILLAN & CO., LIMITED
LONDON · BOMBAY · CALCUTTA MELBOURNE
THE MACMILLAN CO. OF CANADA, LTD.
TORONTO
Computing With Python An Introduction To Python For Science Engineering Claus Fuher
The Metamorphosis of a Bontoc Igorot.
Two photographs of a Pít-a-pit, a Bontoc Igorot boy. The
second was taken nine years after the first.
The Philippines Past
and Present
By
Dean C. Worcester
Secretary of the Interior of the
Philippine Islands 1901–1913;
Member of the Philippine
Commission, 1900–1913
Author of “The Philippine Islands and
Their People”
In Two Volumes — With 128 Plates
Volume II
New York
The Macmillan Company
1914
All rights reserved
Copyright, 1914,
By THE MACMILLAN COMPANY.
Set up and electrotyped. Published February, 1914.
Norwood Press
J. S. Cushing Co.—Berwick & Smith Co.
Norwood, Mass., U. S. A.
Computing With Python An Introduction To Python For Science Engineering Claus Fuher
Contents
Vol. II
Chapter Page
XIX. Education 501
XX. The Exploration of Non-Christian Territory 532
XXI. The Government of Non-Christian Tribes 559
XXII. The Government of Non-Christian Tribes
(Continued)
591
XXIII. Corrigenda 637
XXIV. Non-Christian Tribe Problems 660
XXV. Slavery and Peonage 676
XXVI. Murder as a Governmental Agency 730
XXVII. The Philippine Legislature 768
XXVIII. The Picturesque Philippines 792
XXIX. Rod, Shotgun and Rifle 806
XXX. Philippine Lands 829
XXXI. Philippine Forests 846
XXXII. Improved Means of Communication 861
XXXIII. Commercial Possibilities of the Philippines 884
XXXIV. Peace and Prosperity 911
XXXV. Some Results of American Rule 921
XXXVI. Is Philippine Independence now Possible? 933
XXXVII. What Then? 961
Appendix
Instructions to the First Philippine Commission
975
Proclamation of the First Philippine
Commission 977
Instructions to the Second Philippine
Commission 980
Past and Present Organization of the Courts
of the Philippine Islands 988
Present accepted Estimate of the Non-
Christian Population of the Philippines 999
Index 1005
List of Illustrations
Vol. II
The Metamorphosis of a Bontoc Igorot Frontispiece
Facing page
Head-hunters’ Weapons 508
The Three Leading Men in the Funeral Procession of an Ifugao who
has lost his Head to the Enemy 516
The Sacred Tree of the Ifugaos 524
Entrance to the Quiangan Schoolhouse 534
An Ifugao School 540
The Sub-provincial Building at Quiangan 546
Ifugao Constabulary Soldiers 554
Bontoc Igorot Head-hunters 562
Bontoc Igorot Women in Banana-leaf Costume 570
A Bontoc Igorot Tug-of-war 578
Bontoc Igorot Boys learning to make Furniture 586
A Conference with Ifugao Chiefs 594
Finished Trail built by Ifugaos 602
Difficult Bit of Rock Work on the Mountain Trail in Benguet 610
A Flying Ferry in Operation 618
A Wild Tingian of Apayao 626
Tingian Girls threshing Rice 634
Typical Manobos 640
An Old Bukidnon Chief 650
Typical Street in a Filipino Town 656
A Typical Bukidnon Village Street 656
A Typical Improved Bukidnon House 664
A Typical Neglected Filipino House 664
Making Friends with the Mandayas 670
A Mandayan Boy 678
A Group of Bagobos 686
Moro Boats coming out to meet the Philippine Commission at Jolo
692
Among the Moros 700
A Moro Chief with his Wives and Daughter 706
Lieutenant-Governor Manuel Fortich of Bukidnon 708
Governor Frederick Johnson of Agusan 714
A Typical Peon 722
The Penalty for Loyalty to the United States 728
The Philippine Assembly in Session 738
Señor Sergio Osmeña, Speaker of the Philippine Assembly 742
The Manila Hotel 750
Mayon Volcano 756
The Crater of Taal Volcano 764
A Bit of the Pagsanjan Gorge 772
A Giant Tree Fern 780
Scene on a Bird Island 788
A Day’s Catch 796
After the Hunt 804
Typical Scene at the Edge of a Hardwood Forest 812
A Typical Forest Scene 820
Old-style Road across Lowlands 826
New-style Road across Lowlands 826
Typical Old-style Country Road 836
Typical New-style Country Road 836
A Canga, or Carabao Sledge 844
A New-style Cart, with Broad-tired Wheels, which does not injure the
Roads 844
Road Destroyers at Work 852
An Old-style Culvert 858
The Old Way of Crossing a River 868
The New Way of Crossing a River 868
A Typical Old-style Bridge 878
A Typical Reënforced Concrete Bridge 878
A Collapsible Bridge 886
Map: Manila, the Future Distributing Centre for the Far East 888
Preparing Rice Land for Planting 892
Planting Rice 892
A Three-year-old Coffee Bush 902
A Ceara Rubber Tree 906
A Typical Cocoanut Grove 918
A Typical Filipino Town 922
A Typical Group of Filipinos 930
A Typical Spanish Mestiza 938
A Strange Couple 946
A Member of the Cabaruan Trinity 946
A Typical Old-style Provincial Government Building 962
A Modern Provincial Government Building 962
A Refuge from the Moros 968
A Possible Office-holder 972
Computing With Python An Introduction To Python For Science Engineering Claus Fuher
The Philippines Past and Present
Chapter XIX
Education
No work accomplished since the American occupation is of more fundamental and far-
reaching importance than that of the Bureau of Education. In order to appreciate it one
must gain some familiarity with the conditions which prevailed in Spanish times.
The first evidence of the Spanish governmental attitude toward education in the
Philippines is found in a royal edict of March 21, 1634,1 in which Felipe IV orders all
archbishops and bishops to take steps for the education of the Filipinos in the Spanish
language and in Christian doctrine.
That this decree was more honoured in the breach than in the observance is evident from
another royal decree of June 20, 1686,2 in which the king reminds civil and religious
authorities that the non-observance of the decree of 1634 will be charged against them.
Neither of these documents provided for financing the scheme of education ordained, but
a decree of December 22, 1792,3 did make financial provision for the establishment of
Spanish schools for natives. The salaries of teachers were to be paid from the royal
treasury, and deficits were to be made up from the communal properties and treasuries.
Although this was the first practical attempt to introduce general native education, there
are evidences that individual opportunities were offered to, and embraced by, Filipinos.
It is probable, too, that in certain localities the most generous of the Spaniards opened
private schools.
The College of San José was founded in 1601, the University of Santo Tomás in 1619.
Neither made provision for educating natives. They were established for the children of
Spaniards only, although both later admitted Filipinos. But in the rules for the short-lived
college of San Felipe (1641–1645),4 Corcuera lays down the following: “The college
servants shall be of influential Pampango families, and they shall be taught to read and
write in the Spanish language, and shall be given clerkships if they show aptitude
therefor.” We learn that when the charity school of San Juan de Letran passed under the
control of the Dominicans in 1640, native boys were admitted, on payment of fees, to
share the advantages offered charitably to Spanish orphans.5
Primary education for Filipinos secured no real foothold until 1863.6 In that year, by
royal decree, a school system originally planned for Cuba was extended to the
Philippines. It made provision for the beginnings of primary instruction in all
municipalities of the islands. A summary7 called forth by a circular of March 1, 1866,
gives information with regard to the progress actually made. This summary fixes the
number of towns at nine hundred, the number of children attending school at one
hundred thirty-five thousand boys and twelve thousand two hundred sixty girls, and the
number of schools at sixteen hundred seventy-four, but it gives the number of buildings
actually in use for schools as only six hundred forty-one. Instruction in Spanish was not
always, or even generally, given.
In 1863 provision was also made for the establishment of a normal school at Manila. In
1893,8 forty years later, the actual appropriation for the Normal School was $5525.
Fourteen years after the American occupation, the appropriation for the Normal School
was $56,476.42, in addition to $224,500 spent for new buildings and furniture.9
In 1892 there were two thousand one hundred seventy-three schools. The attendance of
these schools was small and irregular. In 1896, at the outbreak of the insurrection, the
Spanish had in operation a public school system which could call upon the Normal
School for teachers and also upon such graduates of private schools as cared to
undertake the work. Naturally the latter were few. Between 1863 and 1893, the Normal
School had enrolled two thousand and one students.
This may be contrasted with the number of schools which, under the present régime,
prepare the pupils for teaching, as well as for other occupations. Including the students
of the Philippine Normal School, the Philippine School of Arts and Trades, the
Provincial High and Intermediate Schools, nearly thirty-seven thousand pupils are now
following studies which fit them more or less to undertake the work of giving instruction
to others.
In addition to the Normal School, the Spanish established a Nautical School in 1820, a
School of Commercial Accounting and of the French and English Languages in 1839,
and an Academy of Drawing and Painting. Their final system of public instruction was
not badly planned, but it was never actually put into full operation.
From the beginning of the insurrection against Spain in 1896 until the beginning of the
insurrection against the United States in 1899, most of the public schools were closed.
The schoolhouses were used for barracks, prisons, or hospitals. No attempt was made to
keep them in repair, and what scanty equipment they had once possessed was for the
most part destroyed or stolen.
Between 1899 and 1901, many of these buildings were repaired in towns which were
occupied by American soldiers, and the beginnings of a public school system were made
by our victorious army. Wherever our flag was raised a public school was soon
established, soldiers often serving as teachers, and the moral effect of this upon the
Filipinos was very great.
The city of Manila was naturally the first place to receive attention. Three weeks after
our army entered it on August 13, 1898, seven schools were opened under the
supervision of Father W. D. McKinnon, chaplain of the first California Regiment. In
June, 1899, Lieutenant George P. Anderson was detailed as city superintendent of
schools for Manila, and during the following school year he had an average of forty-five
hundred pupils enrolled in the primary schools. Captain Albert Todd was detailed to act
as superintendent of schools for the islands, but on May 5, 1900, in anticipation of the
transfer of the islands from military to civil government, he gave way to Dr. Fred W.
Atkinson, who had been chosen by the Philippine Commission as superintendent of
public instruction. This title was changed later to that of director of education.
On January 21, 1901, the commission passed Act 74, the basis of the present school law.
It provided for the appointment of one thousand American teachers to begin the work of
establishing a school system carried on in English. Appointments were made as rapidly
as possible. By the end of the year, seven hundred sixty-five American teachers were at
work.
When provision was made for the appointment of this large number of Americans, it was
with the idea that they should act as teachers of English in schools over which there
should be Filipino principals, but there was, at that time, no body of Filipino teachers
properly prepared to carry on school work, and by force of circumstances, this plan was
soon altered.
Ten school divisions were established, covering the archipelago. Each was presided over
by a division superintendent of schools. The teachers were theoretically subject to his
control, but the divisions were so large that it was impossible for him to exercise control
very effectively. It is perhaps well that many of the teachers were left free to employ
their own ingenuity in meeting local conditions.
The school system finally established represents a composite of the recommendations of
hundreds of teachers scattered throughout the archipelago, and these recommendations
were based on hard-earned experience.
One of the first duties of teachers was to begin the training of Filipino assistants. This
took form in the organization of so-called aspirante classes, into which the best of the
Filipino youth who were old enough to teach, and who had already received some
education, were gathered. These aspirante classes were often held side by side with
classes in the primary schools first established by American teachers, and by the
beginning of the year 1902 some of the brightest pupils were able to assist in primary
school work. These classes made possible the establishment of organized primary
schools under the control of American teachers with Filipino teachers in the lower
grades. Their graduates formed the nuclei of the first secondary schools, which were
established in 1903.
The difficulties which teachers had to overcome at the outset were numerous. In some of
the older and richer towns there were stone or brick schoolhouses more or less fit for
occupation. In such cases a small number of old wooden benches and a few square feet
of blackboard were usually available. Sometimes there were books provided by the
army: Baldwin’s readers in English or in rudely translated vernacular; Frye’s
geographies translated into Spanish; and possibly Spanish editions of the history of the
United States. This stock was greatly improved during the latter half of 1902, and
teachers were furnished books and supplies as rapidly as transportation facilities
permitted.
In 1901 the number of school divisions was increased to eighteen, and in 1902 to thirty-
six, making the school divisions identical with the thirty-six then existing political
subdivisions of the islands. The organization of the public school system gradually
crystallized and assumed something of the form which it has to-day. Barrio10 schools
were opened, and the work of American teachers who were detailed to supervise them
was thus greatly increased.
The school system took permanent shape in 1903 and 1904. As it now stands it is
controlled by the director of education, who is responsible for its conduct. Serving with
him, and subject to his control, are an assistant director and a second assistant director.
The directors have immediate charge of the general office, which has the following
divisions: records, accounting, buildings, property, academic, industrial and publications.
Each has a chief who is directly responsible for its work.
The islands are now divided into thirty-four school divisions, corresponding, except in
two cases, to provinces. Each has its superintendent of schools.
The divisions are subdivided into districts, over each of which there is a supervising
teacher who is responsible for the conduct of its work. Certain of the intermediate
schools are under supervising teachers, while others are directly under division
superintendents.
The school system to-day extends to the remotest barrios. It is organized and equipped
for effective work, and ready to carry out promptly and effectively the policies
determined upon by the central office.
In each province there is a central provincial school offering intermediate and secondary
courses. Only twelve of them now give a full four-year course. Others offer three years,
two years or one year of secondary work. There is also a manual training department
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Programming And Scientific Computing In Python 60 Jm Hoekstra
DOCX
ONLINE ACCESSThank you for purchasing a new copy of In.docx
PDF
The Python Workshop.pdf
PDF
Class 12 Ip Whole Text Book Preeti Arora
PDF
Building Python Programs 1st Edition Stuart Reges Marty Stepp
PPTX
What is Python? An overview of Python for science.
PDF
5444e9539abc6 1294389-sample (3)
PDF
A Whirlwind Tour Of Python
Programming And Scientific Computing In Python 60 Jm Hoekstra
ONLINE ACCESSThank you for purchasing a new copy of In.docx
The Python Workshop.pdf
Class 12 Ip Whole Text Book Preeti Arora
Building Python Programs 1st Edition Stuart Reges Marty Stepp
What is Python? An overview of Python for science.
5444e9539abc6 1294389-sample (3)
A Whirlwind Tour Of Python

Similar to Computing With Python An Introduction To Python For Science Engineering Claus Fuher (20)

PDF
Python Programming A Stepbystep Guide To Learning The Language C K Dhaliwal
PPTX
_python Raunak.pptx
PDF
Py tut-handout
PDF
Introduction-To-Python- a guide to master
PPTX
Introduction_to_Python.pptx
PDF
A Simple Introduction To Python Stephen Lynch
PDF
Python_Crash_Course_2nd_Edition.pdf
PDF
Exploratory Analytics in Python provided by EY.pdf
PDF
Class 01 - Intro.pdf
PPTX
Python Demo.pptx
PDF
Introduction to Python Syntax and Semantics
PPTX
Python avinash
PDF
Python Programming Hans-petter Halvorsen.pdf
PPTX
Python Demo.pptx
PDF
Python-content-1.pdf
PDF
thinkCSpy
PDF
Introduction To Data Science Laura Igual Santi Segu
PDF
Making use of Python 1st Edition Rashi Gupta
PDF
Mastering the Interview: 50 Common Interview Questions Demystified
PDF
Making use of Python 1st Edition Rashi Gupta
Python Programming A Stepbystep Guide To Learning The Language C K Dhaliwal
_python Raunak.pptx
Py tut-handout
Introduction-To-Python- a guide to master
Introduction_to_Python.pptx
A Simple Introduction To Python Stephen Lynch
Python_Crash_Course_2nd_Edition.pdf
Exploratory Analytics in Python provided by EY.pdf
Class 01 - Intro.pdf
Python Demo.pptx
Introduction to Python Syntax and Semantics
Python avinash
Python Programming Hans-petter Halvorsen.pdf
Python Demo.pptx
Python-content-1.pdf
thinkCSpy
Introduction To Data Science Laura Igual Santi Segu
Making use of Python 1st Edition Rashi Gupta
Mastering the Interview: 50 Common Interview Questions Demystified
Making use of Python 1st Edition Rashi Gupta
Ad

Recently uploaded (20)

PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
PDF
Indian roads congress 037 - 2012 Flexible pavement
PDF
Trump Administration's workforce development strategy
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PPTX
Computer Architecture Input Output Memory.pptx
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Introduction to Building Materials
PDF
Empowerment Technology for Senior High School Guide
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
What if we spent less time fighting change, and more time building what’s rig...
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
Indian roads congress 037 - 2012 Flexible pavement
Trump Administration's workforce development strategy
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
Computer Architecture Input Output Memory.pptx
Computing-Curriculum for Schools in Ghana
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Introduction to Building Materials
Empowerment Technology for Senior High School Guide
A powerpoint presentation on the Revised K-10 Science Shaping Paper
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
Paper A Mock Exam 9_ Attempt review.pdf.
What if we spent less time fighting change, and more time building what’s rig...
Ad

Computing With Python An Introduction To Python For Science Engineering Claus Fuher

  • 1. Computing With Python An Introduction To Python For Science Engineering Claus Fuher download https://ebookbell.com/product/computing-with-python-an- introduction-to-python-for-science-engineering-claus- fuher-5903416 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Computing With Python An Introduction To Python For Science And Engineering Feuhrer https://ebookbell.com/product/computing-with-python-an-introduction- to-python-for-science-and-engineering-feuhrer-22059306 Computational Mathematics An Introduction To Numerical Analysis And Scientific Computing With Python Dimitrios Mitsotakis https://ebookbell.com/product/computational-mathematics-an- introduction-to-numerical-analysis-and-scientific-computing-with- python-dimitrios-mitsotakis-50292792 An Introduction To Scientific Computing With Matlab And Python Tutorials Sheng Xu https://ebookbell.com/product/an-introduction-to-scientific-computing- with-matlab-and-python-tutorials-sheng-xu-42864256 Scientific Computing With Python 3 An Examplerich Comprehensive Guide For All Of Your Python Computational Needs 1st Edition Claus Fuhrer Jan Erik Solem Olivier Verdier https://ebookbell.com/product/scientific-computing-with-python-3-an- examplerich-comprehensive-guide-for-all-of-your-python-computational- needs-1st-edition-claus-fuhrer-jan-erik-solem-olivier-verdier-32704550
  • 3. Distributed Computing With Python Pierfederici Francesco https://ebookbell.com/product/distributed-computing-with-python- pierfederici-francesco-22066648 Scientific Computing With Python Highperformance Scientific Computing With Numpy Scipy And Pandas 2nd Edition Claus Fuhrer Jan Erik Solem Olivier Verdier https://ebookbell.com/product/scientific-computing-with-python- highperformance-scientific-computing-with-numpy-scipy-and-pandas-2nd- edition-claus-fuhrer-jan-erik-solem-olivier-verdier-33789050 Numerical Computing With Python Harness The Power Of Python To Analyze And Find Hidden Patterns In The Data 1st Edition Pratap Dangeti Allen Yu Claire Chung Aldrin Yim Theodore Petrou https://ebookbell.com/product/numerical-computing-with-python-harness- the-power-of-python-to-analyze-and-find-hidden-patterns-in-the- data-1st-edition-pratap-dangeti-allen-yu-claire-chung-aldrin-yim- theodore-petrou-7351196 Scientific Computing With Python Mastering Numpy And Scipy 1st Edition John Smith https://ebookbell.com/product/scientific-computing-with-python- mastering-numpy-and-scipy-1st-edition-john-smith-58531304 Scientific Computing With Python 2nd Edition 2nd Claus Fhrer https://ebookbell.com/product/scientific-computing-with-python-2nd- edition-2nd-claus-fhrer-51012512
  • 5. CiausFiihrer Jan Erik Solem Olivier Verdier COMPUTING WITH PYTHON An introduction to Python for science and engineering v M -5 >-« >•-, - > - t - * X > 5C J *c > > p - s V p CP' * ■*a* * 05 ALWAYS LEARNING PEARSON
  • 6. COMPUTING WITH PYTHON AN INTRODUCTION TO PYTHON FOR SCIENCE AND ENGINEERING
  • 7. PEARSON At Pearson, we take learning personally. Our courses and resources are available as books, online and via multi-lingual packages, helping people learn whatever, wherever and however they choose. We work with leading authors to develop the strongest learning experiences, bringing cutting-edge thinking and best learning practice to a global market. We craft our print and digital resources to do more to help learners not only understand their content, but to see it in action and apply what they learn, whether studying or at work. Pearson is the world's leading learning company. Our portfolio includes Penguin, Dorling Kindersley, the Financial Times and our educational business, Pearson International. We are also a leading provider of electronic learning programmes and of test development, processing and scoring services to educational institutions, corporations and professional bodies around the world. Every day our work helps learning flourish, and wherever learning flourishes, so do people. To learn more please visit us at: www.pearson.com/uk
  • 8. COMPUTING WITH PYTHON AN INTRODUCTION TO PYTHON FOR SCIENCE AND ENGINEERING Claus Fuhrer, Jan Erik Solem and Olivier Verdier PEARSON Harlow, England • London • New York • Boston • San Francisco • Toronto • Sydney • Auckland • Singapore • Hong Kong Tokyo • Seoul • Taipei • New Delhi • Cape Town • Sao Paulo • Mexico City • Madrid • Amsterdam • Munich • Paris • Milan
  • 9. PEARSON EDUCATION LIMITED Edinburgh Gate Harlow CM20 2JE United Kingdom Tel: +44 (0)1279 623623 Web; www.pearson.com/uk First published 2014 (print and electronic) © Pearson Education Limited 2014 (print and electronic) The rights of Glaus Fiihrer, Jan Erik Solem and Olivier Verdier to be identified as authors of this work have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988. The print publication is protected by copyright. Prior to any prohibited reproduction, storage in a retrieval system, distribution or transmission in any form or by any means, electronic, mechanical, recording or otherwise, permission should be obtained from the publisher or, where applicable, a licence permitting restricted copying in the United Kingdom should be obtained from the Copyright Licensing Agency Ltd, Saffron House, 6-10 Kirby Street, London EC1N 8TS. The ePublication is protected by copyright and must not be copied, reproduced, transferred, distributed, leased, licensed or publicly performed or used in any way except as specifically permitted in writing by the publishers, as allowed under the terms and conditions under which it was purchased, or as strictly permitted by applicable copyright law. Any unauthorised distribution or use of this text may be a direct infringement of the author's and the publishers' rights and those responsible may be liable in law accordingly. All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners. 'Python' is a registered trademark of the Python Software Foundation. Pearson Education is not responsible for the content of third-party internet sites. ISBN: 978-0-273-78643-6 (print) British Library Cataloguing-in-Publication Data A catalogue record for the print edition is available from the British Library Library of Congress Cataloging-in-Publication Data Fuhrer, Glaus. Computing with Python : an introduction to Python for science and engineering / Glaus Fuhrer, Jan Erik Solem and Olivier Verdier. pages cm. Includes bibliographical references and indexes. ISBN 978-0-273-78643-6 (print: alkaline paper) 1. Python (Computer program language) 2. Science-Data processing. 3. Engineering-Data processing. I. Solem, Jan Erik. II. Verdier, Olivier. III. Title. QA76.73.P98F84 2013 005.13'3-dc23 2013025146 10 987654321 16 15 14 13 Print edition typeset in Stone Serif 9/11.5 by 73 Print edition printed and bound in Malaysia NOTE THAT ANY PAGE CROSS REFERENCES REFER TO THE PRINT EDITION
  • 10. BRIEF CONTENTS Contents vii Chapter X Iterating 133 Preface ix Chapter XI Error Handling 150 Chapter 1 Introduction 1 Chapter XII Namespaces, Scopes Chapter II Getting Started 6 and Modules 162 Chapter III Variables and Basic Types 14 Chapter XIII Input and Output 168 Chapter IV Container Types 30 Chapter XIV Testing 175 Chapter V Linear Algebra: Arrays 44 Chapter XV Comprehensive Examples 189 Chapter VI Advanced Array Concepts 65 Appendix; Calling MATLAB from Python 203 Chapter VII Plotting 84 Bibliography Python commands index 206 208 Chapter VIM Functions 101 Subject index 210 Chapter IX Classes 114
  • 12. Contents vii V.8 Functions Acting on Arrays 57 Preface ix V.9 Linear Algebra Methods in SciPy V.10 Exercises 60 62 Chapter 1 Introduction 1 1.1 Python vs Other Languages 1 Chapter VI Advanced Array Concepts 65 1.2 Literature 3 VI.1 Array Views and Copies 65 I.3 Installation and Configuration Instructions 3 VI.2 Comparing Arrays 66 1.4 Executing Scripts 4 VI.3 Array Indexing VI.4 Performance and Vectorization 69 71 Chapter II Getting Started 6 VI.5 Broadcasting 73 VI.6 Sparse Matrices 79 II.1 Program and Program Flow 6 11.2 Basic Types 11.3 Loops 7 10 Chapter VII Plotting 84 11.4 Conditional Statements 11 VII.1 Basic Plotting 84 11.5 Functions 11 VII.2 Formatting 87 11.6 Scripts and Modules 12 VII.3 Images and Contours 91 11.7 Interpreter 13 VII.4 Useful Toolkits VI1.5 Exercises 93 99 Chapter III Variables and Basic Types 14 111.1 Variables 14 Chapter VIII Functions 101 III.2 Numeric Types 15 VIII.1 Basics 101 III.3 Booleans 21 VIII.2 Parameters and Arguments 102 III.4 Strings 24 VIII.3 Return Values 106 III.5 Exercises 27 VIII.4 Recursive Functions VIII.5 Function Documentation 107 108 Chapter IV Container Types 30 VIII.6 Functions are Objects 109 VIII.7 Anonymous Functions - the lambda IV.I Lists 30 Keyword 110 IV.2 Arrays 36 VIII.8 Functions as Decorators 112 IV.3 Tuples 37 VIII.9 Exercises 113 IV.4 Dictionaries 38 IV.5 Sets IV.6 Container Conversions and Summary 40 41 Chapter IX Classes 114 IV.7 Type Checking 41 IX.1 Introduction 115 IV.8 Exercises 42 IX.2 Attributes IX.3 Subclassing and Inheritance 116 126 Chapter V Linear Algebra: Arrays 44 IX.4 Encapsulation 128 IX.5 Classes as Decorators 129 V.I Overview 44 IX.6 Exercises 131 V.2 Mathematical Preliminaries 47 V.3 The Array Type V.4 Array Indexing 49 51 Chapter X Iterating 133 V.5 Functions to Construct Arrays 53 X.1 The for statement 133 V.6 Accessing and Changing the Shape 53 X.2 Iterators 135 V.7 Stacking 56
  • 13. VIII Contents X.3 List Filling Patterns 141 X.4 When Iterators Behave as Lists 144 X.5 Iterator Objects 145 X.6 Infinite Iterations 146 X.7 Exercises 148 Chapter XI Error Handling 150 XI.1 Exceptions 150 XI.2 Debugging 157 Chapter XII Namespaces, Scopes and Modules 162 XII.1 Namespace 162 XII.2 Scope of a Variable 163 XII.3 Modules 164 Chapter XIII Input and Output 168 XIII.1 File Handling 168 XIII.2 NumPy Methods 170 XIII.3 Pickling 171 XIII.4 Shelves 172 XIII.5 Reading and Writing Matlab Data Files 173 XIII.6 Reading and Writing Images 173 Chapter XIV Testing 175 XIV. 1 Manual Testing 175 XIV.2 Automatic Testing 176 XIV.3 Measuring Execution Time 184 XIV.4 Exercises 188 Chapter XV Comprehensive Examples 189 XV.1 Polynomials 189 XV.2 Spectral Clustering 196 XV.3 Solving Initial Value Problems 199 XV.4 Exercises 202 Appendix: Calling MATLAB from Python 203 Bibliography 206 Python commands index 208 Subject index 210
  • 14. PREFACE This book is the outcome of a course on Python® for scientific computing which has been taught at Lund University since 2008. The course expanded over the years, and condensed versions of the material were taught at universities in Cologne, Trondheim, Stavanger, Soran and also in computational oriented companies. Our belief is that Python and its surrounding scientific computing ecosystem - SciPy, NumPy and matplotlib - represent tremendous progress in the scientific computing en- vironment. Python and the aforementioned libraries are free and open source. What's more, Python is a modern language featuring all the bells and whistles that this adjective entails: object oriented programing, testing, advanced Python shell with IPython, etc. The typical reader of this book will already have some experience in programing, and some taste for scientific computing or mathematics. Our goal is to explain to those readers the steps to get started with Python in the context of scientific computing. The book may be read either from the first page to the last, or by picking the bits that seem most interesting. Needless to say, as improving one's programing skills requires considerable practice, it is highly advisable to experiment and play with the examples and the exercises in the book. We hope that readers will enjoy programing with Python, SciPy, NumPy and matplotlib as much as we do. We would like to express our gratitude towards the reviewers of this book: Linda Kann, KTH Stockholm, Hans Petter Langtangen, Simula Research Laboratory, and Alf Inge Wang, NTNU Trondheim. This book benefited from many helpful comments and suggestions by Helmut Pod- haisky, Halle University, Tony Stillfjord and Christian Andersson, Lund University, and students and teaching assistants from the course 'Berakningsprogramering med Python' over the years. Finally, we would like to express our thanks for the fruitful collaboration with the pub- lisher during the production process, in particular to Philippa Fiszzon. The Authors September 27, 2013
  • 16. CHAPTER I Introduction 1.1 Python vs Other Languages When it comes to deciding what language to use for a book on scientific computing many factors come in to play. The learning threshold of the language itself is important for newcomers, here scripting languages usually provide the best options. A wide range of modules for numerical computing is necessary, preferably with a strong developer com- munity. If these core modules are built on a well-tested, optimized foundation of fast libraries like e.g. LAPACK, even better. Finally, if the language is also usable in a wider setting and a wider range of applications, the chance of the reader using the skills learned from this book outside an academic setting is greater. Therefore the choice of Python was a natural one. In short, Python is • free and open source • a scripting language, meaning that it is interpreted • a modern language (object oriented, exception handling, dynamic typing etc.) • concise, easy to read and quick to learn • full of freely available libraries, in particular scientific ones (linear algebra, visualiz- ation tools, plotting, image analysis, differential equations solving, symbolic compu- tations, statistics etc.) • useful in a wider setting: scientific computing, scripting, web sites, text parsing, etc. • widely used in industrial applications 1.1.1 Python vs other languages There are other alternatives to Python. Some of them and the differences to Python are listed here. Java, C++ Object oriented, compiled languages. More verbose and low level com- pared to Python. Few scientific libraries. c, Fortran Low level compiled languages. Both languages are extensively used in scientific computing, where computational time matters. Nowadays these languages are often combined with Python wrappers. php, ruby Other interpreted languages. PHP is web oriented. Ruby is as flexible as Python but has few scientific libraries. matlab, SciLab, Octave MATLAB is a tool for matrix computation that evolved for scientific computing. The scientific library is huge. The language features are not
  • 17. Chapter I Introduction as developed as those of Python. Neither free nor open source. SciLab and Octave are open source tools which are syntacticly similar to MATLAB. Haskell Haskell is a modern functional language and follows different programing paradigms than Python. There are some common constructions like list comprehen- sion. Haskell is rarely used in scientific computing. See also [11]. 1.1.2 Examples Python is a scripting language that may be used in interactive mode, meaning that you type commands at a prompt: »> x = 3 >» y = 5 »> print (x + y) 8 Here we solve the system of equations G TT) using SciPy: »> import scipy. linalg as si »> M = array ([[!., 2 . ] , [3., 4.]]) »> V = array ( [2 . , 1. ] ) »> x = si. solve (M, V) »> print (x) [-3. 2.5] Computing el7r and 2100 is another example: »> print (exp (Ij *pi) ) # should return -1 (-1+ 1.22464679915e-16j ) »> print (2**100) 1267650600228229401496703205376L So is computing t;(x) — F- ^or = 2 we know that ^(2) = ^: # for x = 2: »> print (scipy . special. zeta (2 . , 1)) 1.64493406685 »> print (pi**2/6) 1.6449340668482264 These examples are meant as a teaser and to give you a sense of the language that we will be exploring in this book.
  • 18. 1.3 Installation and Configuration Instructions 1.2 Literature Here we give some hints to literature on Python which can serve as complementary sources or as texts for parallel reading. Most introductory books on Python are devoted to teach this language as a general purpose tool. One excellent example which we want to men- tion explicitly is [18]. It explains the language by simple examples, e.g. object oriented programing is explained by organizing a pizza bakery. There are very few books dedicated to Python directed towards scientific computing and engineering. Among these few books we would like to mention the two books by Langtangen which combine scientific computing with the modern "pythonic" view on programing, [15, 16]. This "pythonic" view is also the guiding line of our way of teaching programing of numerical algorithms. We try to show how many well-established concepts and construc- tions in computer science can be applied to problems within scientific computing. The pizza-bakery example is replaced by Lagrange polynomials, generators become time step- ping methods for ODEs, and so on. Finally we have to mention the nearly infinite amount of literature on the web. The web was also a big source of knowledge when preparing this book. Literature from the web often covers things that are new, but can also be totally outdated. The web also presents solutions and interpretations which might contradict each other. We strongly recommend to use the web as additional source, but we consider a "traditional" textbook with the web resources "edited" as the better entry point to a rich new world. 1.3 Installation and Configuration Instructions Before diving into the subject of the book you should have all relevant tools installed on your computer. We will give you some advice and recommend tools you might want. All tools we name are public domain and free1 . 1.3.1 Installation Python and all third-party packages (modules) we use in this book are free. There are currently two major versions of Python; the 2.x branch and the new 3.x branch. The former is the most supported in terms of libraries and contains all the sci- entific tools we need. The last and final major 2.x release is Python 2.7 which is the one we will use in this book. The 3.x branch contains many language improvements but still lacks wide library support and is not backwards compatible with the 2.x branch. To learn more about the difference, see [28]. For this book you need to install: • the interpreter: Python 2.7 • the modules for scientific computing: SciPy with NumPy • the module for graphical representation of mathematical results: matplotlib • the shell: iPython • (optional) a Python related editor, e.g., Spyder, Geany, Editra, DrPython The installation of these depend on your operating system. 'Be aware that things might change; we try to collect updated information on the book's homepage http://www.computingwithpython.com.
  • 19. Chapter I Introduction Ubuntu (Linux) On Linux installation requires that you own administrator rights on your computer. Ubuntu and most Linux distributions come with Python already installed. iPython, an editor, matplotlib, SciPy can be installed using Ubuntu's package manager Synaptic. Fur- thermore we recommend that you install the package installer python-pip. It provides an easy way to install more modules, like pip install assimulo for installing a module for solving differential equations. Windows We recommend to download and install the distribution called python(x,y) from [29]. This distribution is targeted for applications within scientific computing and comes with all relevant modules like SciPy, matplotlib, NumPy. It also comes with the editor Spyder and the IPython shell. Mac OS X Mac OS X comes with Python installed, just like most Linux systems. Later versions of Mac OS X (10.6+) also come with NumPy. A good alternative to install SciPy and matplotlib is to use the package system MacPorts [19]. This will automatically install all dependencies needed and also contains many other useful Python modules. The Scipy Superpack [31] is another good option that installs all the necessary modules. 1.3.2 Configuration Most Python code will, in this book and when you use it for real applications, be collected in files. We recommend that you use the following header in all your Python files: # -*- coding: UTF-8 from future import division from scipy import * from matplotlib.pyplot import * This will • allow you to use any non-ascii character, e.g., "a", "6" (assuming that you use the UTF-8 encoding) • activate a true division mode (1/2 will return 0.5 and not 0) • import many standard modules and functions used in this book, e.g., SciPy. Many editors, e.g. Spyder, provide the possibility to create a template for your files. Look for this feature and put the above mentioned header into a template. 1.4 Executing Scripts Python Shell The Python shell is good but not optimal for interactive scripting. We therefore recom- mend to use IPython instead [27].
  • 20. 1.4 Executing Scripts iPython may be started in different ways, depending on your operating system. • on Linux by running ipython --pylab in a shell • on Windows by creating a shortcut, for which you choose the command python.exe -c "import sys; from IPython.ipapi import launch_new_instance; sys.exit(launch_new_instance())" • on Mac OS X by running ipython --pylab in Terminal Executing Scripts You often want to execute the contents of a file. • Use the command cd in IPython in order to move to the directory where your file is located • To execute the contents of a file named f ile. py just run the command execfile('file.py') in the IPython shell. Getting Help Here are some tips on how to use IPython: • To get help on an object just type ? after the object's name and then return • Use the arrow keys to reuse the last executed commands • You may use the tab key for completion (i.e., you write the first letter of a variable or method, and IPython shows you a menu with all the possible completions) • Use Ctrl+D to quit • Use iPython's magic functions. You find a list and explanations by applying the func- tion %itiagic at command prompt. You can find out more about IPython from the online documentation [14].
  • 21. CHAPTER II Getting Started In this chapter we will give a brief overview over the principal syntactical elements of Python. Readers who are starting to learn programing are guided through the book by this chap- ter. Every topic presented here is in a "how-to" way and will be explained deeper later in the book in a conceptual way and also enriched with many applications and extensions. Readers who are already familiar with another programing language will find the Python way of doing classical language constructs as a way to easily getting started with Python. Both types of readers are encouraged to take this chapter as a brief guideline when zigzagging through the book. 11.1 Program and Program Flow A program is a sequence of statements which are executed in a top-down order. This linear execution order has two important exceptions: • There might be a conditional execution of alternative groups of statements (blocks), which we refer to as branching, • and there are blocks which are executed repetitively, which is called looping, see Figure ILL i Condition Linear Figure 11.1 Program Flow TV Branching Condition Loop Python uses a special syntax to mark blocks of statements: a keyword, a colon and an indented sequence of statements, which belong to the block, see Figure II.2. Comments If a line in a program contains the symbol # everything following on the same line is considered as a comment: # This is a comment of the following statement a - 3 # ... which might get a further comment here
  • 22. 11.2 Basic Types Colon marks the beginning ofa block. Indentation is mandatory and shows the extent of the block. if a > b: s = a/b else : s = 2*b-a The block ends when the indentation returns to the previous level. Figure 11.2 Example of a block command Line joining A backslash () at the end of the line marks the next line as a continuation line, i.e., explicit line joining. If the line ends before all parentheses are closed the following line will automatically be recognized as a continuation line, i.e., implicit line joining. 11.2 Basic Types Let us go over the basic types that you will encounter in Python. 11.2.1 Numbers A number may be an integer, a real number or a complex number. The usual operations are • + and - addition and subtraction • * and / multiplication and division • ** power. For example, 2** (2+2) # 16 lj**2 # -1 Note the use of the symbol j to denote the imaginary part of a complex number. More on complex numbers can be found in § III.2.3. 11.2.2 Strings Strings are sequences of characters, enclosed by simple or double quotes: 'valid string' "string with double quotes" "you shouldn't forget cornments" 'these are double quotes:
  • 23. Chapter II Getting Started You may also use triple quotes for strings including multiple lines: """This is a long, long string""" 11.2.3 Variables A variable is a reference to an object. An object may have several references. One uses the assignment operator = to assign a value to a variable: x = [3, 4] # a list object is created y = x # this object now has two labels: x and y del x # we delete one of the labels del y # both labels are removed: the object is deleted The value of a variable can be displayed by the print command1 : x - [3, 4] # a list object is created print(x) 11.2.4 Lists Lists are a very useful construction and one of the basic types in Python. A Python list is an ordered list of objects enclosed by square brackets. One accesses elements of a list using zero-based indexes inside square brackets: LI = [5, 6] Ll[0] # 5 LI[1] #6 Ll[2] # raises IndexError L2 = ['a', 1, [3, 4]] L2 [0] # 'a' L2[2][0] # 3 L2[-l] # last element: [3,4] L2[-2] # second to last: 1 Indexing of the elements starts at zero. One can put objects of any type inside a list, even other lists. Some basic list functions are: • range (n) creates a list with n elements, starting with zero. print(range(5)) # returns [0, 1, 2, 3, 4] 'In this book we use the print () command with parentheses which is standard in Python 3.x.
  • 24. 11.2 Basic Types • len gives the length of a list. lenfl'a', 1, 2, 34]) # returns 4 • append appends an element to a list. L = [ 'a', 'b', 'C ] L [ -1 ] # 'C L.append('d') L # L is now ['a', 'h', 'c', 'd'] L [-1] # '6' Operations on Lists • The operator + concatenates two lists: LI = [1, 2] L2 = [3, 4] L = Ll + L2 # [1, 2, 3, 4] • As one might expect, multiplying a list with an integer concatenates the list with itself several times: n*L is equivalent to L + L H + L. n times L = [1, 2] 3 * L # [1, 2, 1, 2, 1, 2] 11.2.5 Boolean Expressions A Boolean expression is an expression that may have the value True or False. Some common operators that yield conditional expressions are: ==, equal ! =, not equal <, <=, less than, less than or equal >, >=, greater than, greater than or equal One combines different Boolean values with or and and. The keyword not gives the log- ical negation of the expression that follows. Comparisons can be chained so that for example x < y < z is equivalent to x < y and y < z. The difference is that y is only evaluated once in the first example. In both cases z is not evaluated at all when the first condition, x < y, evaluates to False. 2 >= 4 # False 2 < 3 < 4 # True 2 < 3 and 3 < 2 # False 2 != 3 < 4 or False # True 2 <= 2 and 2 >= 2 # True not 2 == 3 # True not False or True and False # True!
  • 25. Chapter II Getting Started Note the precedence rules: <, >, <=, >=, ! = , == have higher precedence than not. The operators and, or have lowest precedence. 11.3 Loops Loops are used to repetitively execute a sequence of statements while changing a variable from iteration to iteration. This variable is called index variable. It is successively assigned to the elements of a list, see § X.l: L = [1, 2, 10] for s in L: print(s * 2) # output: 2 4 20 The part to be repeated in the for loop has to be properly indented: for elt in my_list; do_something() something_else{) etc print("loop finished") # outside the for block 11.3.1 Repeating a Task One typical use of a for loop is to repeat a certain task a fixed number of times: n = 30 for iteration in range(n): do_something # this gets executed n times II.3.2 break and else The for statement has two important keywords: break and else. break quits the for loop even if the list we are iterating is not exhausted. for x in x_values: if x > threshold: break print(x) else checks whether the for loop was broken with the break keyword. If it was not broken the block following the keyword else is executed. for x in x_values: if x > threshold: break else: print("all the x are below the threshold")
  • 26. 11.5 Functions 11.4 Conditional Statements This section covers how to use conditions for branching, breaking or otherwise controlling your code. A conditional statement delimits a block that will be executed if the condition is true. An optional block, started with the keyword else will be executed if the condition is not fulfilled, Figure II.2: We demonstrate this by printing |x|, the absolute value of x: x = ... if x >= 0: print(x) else: print(-x) f X if X > 0 1 —x otherwise Any object can be tested for truth value, for use in an if or while statement. The rules for how the truth values are obtained are explained in § III.3.2. 11.5 Functions Functions are useful to gather similar pieces of code in one place. Consider the following mathematical function: x f{x) := 2x + 1 The Python equivalent is: def f(x): return 2*x + 1 • the keyword def tells Python we are defining a function • f is the name of the function The start of the function is indicated by the keyword def The function parameters are comma separated. I def / addfargl, arg2) s = argl + arg2 return s The function header ends with a colon. Indentation is not optional and shows what block belongs to the function. The return statement (optional) specifies what is returned by the function. If omitted, the function returns None. Figure 11.3 Anatomy of a function
  • 27. Chapter II Getting Started • x is the argument, or input of the function • what is after return is called the output of the function Once the function is defined it may now be called using: f ( 2 ) # 5 f(l) # 3 • etc. 11.6 Scripts and Modules A collection of statements in a file, (which usually has a py extension), is called a script. Suppose that we put the contents of the following code into a file named smart script. py: def f(x): return 2*x + 1 z = [] for x in range(10): if f(x) > pi: z.append(x) else: z.append(-1) print(z) In a Python or iPython shell such a script can then be executed with a single command execflie('sraartscript.py') 11.6.1 Simple Modules - Collecting Functions Often one collects functions in a script. This creates a module with additional Python functionality: To demonstrate this we create a module by collecting functions in a single file, e.g., smartfunctions.py: def f(x): return 2*x + 1 def g(x): return x**2 + 4*x 5 def h(x): return l/f(x) • These functions can now be used by any external script or directly in the IPython environment. • Functions within the module can depend on each other.
  • 28. 11.7 Interpreter • Grouping functions with a common theme or purpose gives modules that can be shared and used by others. Again the command execfile(' smartfunctions .py') makes these functions avail- able to your iPython shell2 . In Python terminology one says that they are put into the actual namespace. 11.6.2 Using Modules and Namespaces Alternatively, the modules can be imported by the command import. It creates a named namespace. The command from puts the functions into the general namespace. import smartfunctions print(smartfunctions.f(2)) # 5 from smartfunctions import g fimport just this one function print(g(1)) # 0 from smartfunctions import * #import all print(h(2)*f(2)) # I Note that the commands import and from import the functions only once into the re- spective namespace. Changing the functions has no effect for the current Python session. More on modules can be found in § XII.3. 11.7 Interpreter The Python interpreter executes the following steps 1. First run for the syntax 2. Then execute the code line by line 3. Code inside a function or class declaration is not executed (but checked for syntax) def f(x): return y**2 a = 3 # here both a and f are defined You can run the program above because there are no syntactical errors. You get an error when you call the function f, though. f(2) # error, y is not defined 2 Note that there is also the iPython magic function run
  • 29. CHAPTER III Variables and Basic Types In this chapter we will present the most important and basic types in Python. What is a type? It is a set consisting of data content, its representation and all possible operations. Later in this book we will make this definition much more precise, when we introduce the concepts of a class in Chapter IX. 111.1 Variables Variables are references to Python objects. They are created by assignments: a=l diameter=3. height=5. cylinder=[diameter,height] # reference to a list Variables take names which consist of any combination of capital and small letters, the underscore (_), and digits. A variable name must not start with a digit. Note that variable names are case sensitive. A good naming of variables is an essential part of documenting your work, so we rec- ommend to use descriptive variable names. Python has some reserved keywords, which cannot be used as variable names, see Table III.l. An attempt to do so would raise a syntax error. Table 111.1 Reserved Python keywords and as assert break class continue def del eiif else except exec finally for from global if import in is lambda not or pass print raise return try while yield As opposed to other programing languages, Python variables require no type declaration. One can create several variables with a multiple assignment statement: a=:b = c = l#a, h and c get the same value 1
  • 30. III.2 Numeric Types Variables can be altered after their definition a = 1 a = a + 1 # a gets the value 2 a = 3 * a ff a gets the value 6 The last two statements can be written combining the operation with an assignment directly by using increment operators: a += 1 # same as a - a + 1 a *= 3 # same as a = 3 * a 111.2 Numeric Types At some point you will have to work with numbers, so we start by considering different forms of numeric types in Python. In mathematics we distinguish between natural num- bers (N), integers (Z), rational numbers (Q), real numbers (E) and complex numbers (C). These are infinite sets of numbers. Operations differ between these sets and may not even be defined. For example the usual division of two numbers in Z might not result in an integer - it is not defined on Z. In Python, like in many other computer languages, we have numeric types • the numeric type int, which is a finite subset of Z, • the numeric type float, which is a finite subset of E and • the numeric type complex, which is a finite subset of C. As these are finite sets, there is a smallest and a largest number and there is a smallest spacing between numbers, see § III.2.2. 111.2.1 integers The simplest numerical type is the integer type. Plain Integers The statement k = 3 assigns the variable k to an integer. Applying an operation of the type +, -, * to integers returns an integer. Caution: Division in Python The behavior of the division operator with integers is very unintuitive. Compare the fol- lowing expressions: 1/2 # gives the result 0! 1.0/2.0 # gives the result 0.5 In order to obviate this potential pitfall, we strongly advise to start each and every Python file by the following line: from future import division This will activate the true division inside the corresponding file, i.e., the expression 1/2 now returns 0.5. Note that the integer division remains available through the operator //.
  • 31. Chapter III Variables and Basic Types Py3k: True Division is on by Default As this behavior of the division is error-prone it is changed in Python 3. The default division is the true division, i.e., 1/2 always returns 0.5. The set of integers in Python is bounded: {(-2)31 ,..., -1, 0, 1,... 231 - 1). To represent a plain integer 32 bits are used (31 for the number and 1 for the sign). The maximal integer is accessible in the Python variable sys.maxint (after first im- porting the module sys, see § XII.3). Long Integers What happens when a calculation results in a number which exceeds the maximal repre- sentable integer? »> 2**31 21474836481. The result is of another type. It is a long integer. Long integers are displayed by their digits appended by the letter "L". Operations with long integers result in long integers k = 2**31-1 type(k) # returns: <type 'long'> k = int(k) # performs a type conversion to plain integer The expression int(k) converts a number k to a plain integer if k is in the range of plain integers. Otherwise the result is a long integer. The expression long(k) converts k to a long integer. In scientific computing integers are mostly used as counters and long integers are rarely used. In contrast, computations in number theory often require to represent numbers in the unbounded set of long integers. Caution: Performance of Long integers Note that computations with long integers may be significantly slower than with plain integers. Py3k: No distinction integer/long integer In Python 3, there is no distinction between standard and long integers anymore. 111.2.2 Floating Point Numbers Floating Point Representation If you execute the statement a = 3.0 in Python, you create a floating point number (Python type float). These numbers form a subset of the rational numbers, Q.
  • 32. III.2 Numeric Types Alternatively the constant could have been given in exponent notation a = 30. Oe-l or simply a = 30 . e-1. The symbol e separates the exponent from the mantissa and the expression reads in mathematical notation a — 30.0 x 10_1 . The name floating point number refers to the internal representation of these numbers and reflects the floating position of the decimal point when considering numbers over a wide range. Applying the elementary mathematical operations +, *, / to two floating point num- bers or to an integer and a floating point number returns a floating point number. Operations between floating point numbers rarely return the exact result expected from rational number operations: 0.4 - 0.3 # returns 0.10000000000000003 This facts matters, when comparing floating point numbers: 0.4 - 0.3 == 0.1 # returns False see § XIV.2.6. Internally, floating point numbers are represented by four quantities: the sign, the man- tissa, the exponent sign and the exponent: sign(x) (xq + + • • • + with fi eN and Xq # 0, 0 < x,- < p. X().. .xt_] is called the mantissa, p the basis and e the exponent e < U. t is called the mantissa length. The condition xq # 0 makes the representation unique and saves in the binary case {P = 2) one bit. There exist two floating point zeros +0 and -0, both represented by the mantissa being 0. On a typical Intel processor p = 2. To represent a number in the Python type float 64 bits are used, namely 2 bits for the signs, t = 52 bits for the mantissa and 10 bits for the exponent e. With this data the smallest positive representable number is flmin = 1. 2-1023 % IQ-308 and the largest is flmax = 1.111... 1 x 21023 ^ 10308 . Note that floating point numbers are not equally spaced in [0, flmax]. There is in particular a 'huge' gap at zero [32, p. 11]: The distance between 0 and the first positive number is 2-1023 , while the distance between the first and the second is smaller by a factor 2_52 « 2.2 x 10"16 , cf. Figure III.l. This effect is caused by the normalization xq # 0. This gap is filled equidistantly with subnormal floating point numbers to which such a result is rounded. Subnormal floating point numbers have the smallest possible exponent and do not follow the convention that the leading digit xq has to differ from zero, [12]. 0.0 1.0 2.0 I H-H—^—I—^—I Figure 111.1 The floating point gap at zero. Here f = 3, L/ = 1.
  • 33. Chapter III Variables and Basic Types Infinite and Not a Number There are in total 2(^ - l)^f_1 (2[/ + 1) + 1 floating point numbers. Sometimes a numerical algorithm computes numbers outside this range. This generates number over- or underflow. In SciPy a special floating point number inf is assigned to overflow results: >» exp 1000.) inf »> a - inf »> 3 - a -inf »> 3 + a inf Working with inf may lead to mathematically undefined results. This is indicated in Python by assigning the result a special floating point number: nan. This stands for not- a-number, i.e., an undefined result of a mathematical operation: >>> a+a inf »> a-a nan A A A a/a nan There are special rules for operations with nan and inf. For instance, nan compared to anything (even to itself) always returns False: x = nan x < 0 # False x > 0 # False x == x # False See Exercise 4 for some surprising consequences of the fact that nan is never equal to itself. The float inf behaves much more as expected: infinity - inf 0 < infinity # True infinity <= infinity # True infinity -- infinity # True -infinity < infinity # True infinity - infinity # nan A way to check for nan and inf is to use the functions isnan and isinf. Often, one wants to react directly, when a variable gets the value nan or inf. This can be achieved by using the NumPy command seterr. The command sequence seterr(all='raise' ) raises an error, if a calculation would return one of those values.
  • 34. III.2 Numeric Types Underflow: Machine Epsilon Underflow occurs, when an operation results in a rational number which falls into the "gap at zero", see Figure III.l. Definition: Machine Epsilon The machine epsilon or rounding unit is the largest number e such that float(1.0 + £) = 1.0 Notethate ^ ^1_t /2 = 1.1102xl0_16 on most of todays computers. The value which is valid on the actual machine you are running your code on is accessible via the command import sys sys.float_info.epsilon # 2.220446049250313e-16 (depending on your system) If you execute sys. floatJLnfo you get more information about the internal repre- sentation of the float type on your machine. The function float converts other types to a floating point number - if possible. This function is especially useful when converting an appropriate string to a number a = float('1.356'). Other float types in NumPy NumPy also provides other float types, known from other programing languages as single and double precision numbers, namely float64 and float32: a = pi # returns 3.141592653589793 al = float64(a) # returns 3.1415926535897931 a2=float32(a) # returns 3.1415927 a - al # returns 0.0 a - a2 # returns -8. 7422780126189537e-08 The second last line demonstrates that a and al do not differ in accuracy. In the first two lines they only differ in the way they are displayed. The real difference in accuracy is between a and its single precision counterpart a2. The NumPy function f info can be used to display information on these floating point types: f32 = finfo(float32) f32.precision # 6 (decimal digits) f64 = finfo(float64) f64.precision # 15 (decimal digits) f = finfo(float) f.precision # 15 (decimal digits) f64.max # 1. 7976931348623157e+308 (largest number) f32.max # 3.4028235e+38 (largest number) help(finfo) # Check for more options
  • 35. Chapter III Variables and Basic Types 111.2.3 Complex Numbers Complex numbers are an extension of the real numbers frequently used in many scientific and engineering fields. Complex Numbers in Mathematics Complex numbers consist of two floating point numbers, the real part a of the number and its imaginary part b. In mathematics a complex number is written as 2 = « + M, where i defined by i2 = -1 is the imaginary unit. The conjugate complex counterpart of z is z — a — bi. If the real part a is zero the number is called an imaginary number. The j Notation In Python imaginary numbers are characterized by suffixing a floating point number with the letter j, e.g. z = 5.2j. A complex number is formed by the sum of a floating point number and an imaginary number, e.g., z=3.5+5.2 j. While in mathematics the imaginary part is expressed as a product of a real number b with the imaginary unit i, the Python way of expressing an imaginary number is not a product: j is just a suffix to indicate that the number is imaginary. This is demonstrated by the following small experiment: b=5 .2 z=bj # returns a (name) error z=b*j # returns a (name) error z=b*lj # is correct The method conjugate returns the conjugate of z: z=3.2+5.2j z.conjugate() # returns (3.2-5.2j) Real and Imaginary Parts One may access the real and imaginary parts of a complex z using the attributes real and imag. Those attributes are read-only: z — 1 j z.real # 0 z.imag # 1 z.imag — 2 # error Note also that it is not possible to convert a complex number to a real number: z = 1 + Oj z == 1 # True float(z) # error
  • 36. III.3 Booleans Interestingly, the attributes real and imag, as well as the method conjugate work just as well for complex arrays (see Chapter V). We demonstrate this by computing the ]Vth roots of unity which are z/< = ei27tk /N i k = 0,..., N - 1, i.e., the N solutions of zN = 1: N = 10 # the following vector contains the Nth roots of unity: unity_roots = array([exp(Ij*2*pi*k/N) for k in range(N)]) # access all the real or imaginary parts with real or imag: plot(unity_roots.real, unity_roots.imag, 'o') allclose(unity_roots**N, 1) # True It is of course possible to mix the previous methods, as illustrated by the following examples: z=3.2+5.2j (z+z.conjugate())/2. # returns (3.2+0j) ((z+z.conjugate())/2.) .real # returns 3.2 (z-z.conjugate())/2. # returns 5.2j ((z-z.conj ugate())/2.) .imag # returns 5.2 sqrt(z*z.conjugate()) # returns (6.1057350089894991+0j) 111.3 Booleans A Boolean1 variable can take only two values, True and False. The main use of this type is in logical expressions. Here are some examples: a = True b = 30>45 # b gets the value False Boolean expressions are often used in conjunction with the if statement. if x>0: print "positive") else: print "nonpositive") Earned after George Boole (1815-1864).
  • 37. Chapter III Variables and Basic Types Caution: True and False are variables Note that in Python, True and False are merely variables and not reserved keywords (Table 111.1). It means that you may technically redefine those variables as in True = 2 Of course, you should never do that, even if Python allows it, because it will render your code completely unreadable. (To recover, you might simply execute True = 1 > 0, and False = not True.) 111.3.1 Boolean Operators: and, or, not The Boolean operations are performed using the keywords and, or and not in Python. True and False # False False or True # True (30 > 45) or (27 < 30) # True not True # False not (3 > 4) # True The operators follow some precedence rules, see § II.2.5, which would make the paren- theses in the third line and in the last obsolete. It is a good practice to use them anyway to increase the readability of your code. Note that the operator and is implicitly chained in the following Boolean expressions: a < b < c # same as: a < b and b < c a == b == c # same as: a == b and b == c iil.3.2 Boolean Casting Most objects in Python may be converted to Booleans, this is called Boolean casting. The built-in function bool performs that conversion. Note that most objects are cast to True, except zero, the empty tuple, the empty list, the empty string or the empty array. These are cast to False. It is not possible to cast arrays into Booleans, unless they contain no or one element; this is explained further in § VI.2.1. The rules for Boolean casting are summarized in Table III.2. Table 111.2 Rules of conversion to Boolean. bool False True string / / 'not empty' number 0 /o list [] t.. . ] (not empty) tuple () (..,..) (not empty) array array([]) array ( [a] ) (a ^ 0) array array([0,0]) array Exception raised if array contains more than one element
  • 38. III.3 Booleans Some usage examples: bool([]) # False bool(O) # False bool(' ') # True bool('') # False bool('hello') # True bool(1.2) # True bool(array([1])) # True bool(array([1,2])) # Exception raised! Automatic Boolean Casting Using an if statement with a non-Boolean type will cast it to a Boolean. In other words, the following two statements are always equivalent: if a: if bool(a): # exactly the same as above A typical example is a test if a list is empty: # L is a list if L: print("list not empty") else: print("list i s empty") An empty array, list or tuple will return False. You can also use a variable in the if statement, for example an integer: # n is an integer if n % 2: print("n is odd") else: print("n is even") Note that we used % for the modulo operation, which returns the remainder of an integer division. In this case, it returns 0 or 1 as the remainder after modulo 2. In this last example, the values 0 or 1 are cast to bool, see § III.3.4. Boolean operators (or, and, not) will also implicitly convert some of their arguments to a Boolean. 111.3.3 Return values of and and or Note that the operators and and or do not necessarily produce Boolean values.
  • 39. Chapter III Variables and Basic Types The expression x and y is equivalent to def and_as_function(x,y): if not x: return x else: return y and the expression x or y is equivalent to def or_as_function(x,y): if x: return x else: return y Interestingly, this means that when executing the statement True or x, the variable x need not even to be defined! The same holds for False and x. Note that, unlike their counterparts in mathematical logics, these operators are no longer commutative in Python. Indeed, the following expressions are not equivalent: [1] or 'a' # produces [1] 'a' or [1] # produces 'a' 111.3.4 Booleans and Integers In fact, Booleans and integers are the same. The only difference is in the string represen- tation of 0 and 1 which is in the case of Booleans 'False' and 'True' respectively. This allows constructions like this: def print_ispositive(x): possibilities=['nonpositive', 'positive'] return "x is {}".format(possibilities[x>0]) #(for the format method see § III.4.2) We note for the readers already familiar with the concept of subclasses, that the type bool is a subclass of the type int, cf., § IX.3. Indeed all four inquiries isinstance (True, bool), isinstance(False, bool), isinstance(True, int), and isinstance (False, int) return the value True, see § IV.7. Even rarely used statements like True+13 are syntactically correct. 111.4 Strings The type string is a type used for text: name = 'Johan Carlsson' child = "Anna is Johan Carlsson's daughter" book = " " "Aunt Julia and the Scriptwriter" " "
  • 40. III.4 Strings 25 A string is enclosed either by single or double quotes. If a string contains several lines it has to be enclosed by three double quotes "" or three single quotes '' Strings can be indexed with simple indexes or slices (see § IV. 1.1 for a comprehensive explanation on slices.) book[-l] # returns 'r' book[-12:] # returns 'Scriptwriter' Strings are like tuples immutable, i.e., items cannot be altered. The command book [ 1 ] =' a' returns TypeError: 'str' object does not support item assignment The string 'n' is used to insert a line break (LF linefeed) and 't' inserts a horizontal tabulator (TAB) into the string to align several lines print('Temperature: t20tCnPressure:t5tPa') These strings are examples of escape sequences. Escape sequences always start with a backslash ''. A multiline string automatically includes escape sequences: a= A multiline example" " " a # returns 'nA multilinenexample' 111.4.1 Operations on strings and string methods Addition of strings performs concatenation: last_name='Carlsson' f irst_name='Johanna' Full_name=first_name+' '+last_name # returns 'Carlsson Johanna' Multiplication is just repeated addition: game=2*'Yo' it returns 'YoYo' When strings are compared, lexicographical order applies and the upper-case form precedes the lower-case form of the same letter: 'Anna' > 'Arvid' # returns false 'ANNA' < 'anna' # returns true '10B' < '11A'# returns true
  • 41. Chapter III Variables and Basic Types Among the variety of string methods we mention here only the most important ones: • Splitting a string: The split method generates a list from a string by using a single or multiple blank as a separator. Alternatively an argument can be given specifying a particular string as a separator: text='quod erat demonstrandum' text.split() # returns ['quod', 'erat', 'demonstrandum'] table='Johan;Carlsson;19890327' table.split(';') # returns ['Johan','Carlsson','19890327'] king='CarlXVIGustaf' king.split('XVI') # returns ['Carl', 'Gustaf'] • Joining a list to a string: this is the reverse operation to split sep=';' sep.join(['Johan','Carlsson','19890327']) # returns 'Johan; Carlsson;19890327' • Searching in a string: The find method returns the first index in the string, where a given search string starts. If the search string is not found -1 is returned: birthday^'20101210' birthday.find('10') # returns 2 111.4.2 String Formatting String formatting is done using the format method: course_code = "NUMA21" print("This course's name is {}".format(course_code)) # This course's name is NUMA21 The function format is a string method, which scans the string for the occurrence of placeholders, which are enclosed by curly brackets. These placeholders are replaced in a way specified by the argument of the format method. How they are replaced depends on the format specification defined in each {} pair. Format specifications are indicated by a colon as their prefix. The format method offers a range of possibilities to customize the formatting of objects depending on their types. Of particular use in scientific computing are the formatting options for the float type. One may choose either the standard fixed point notation with {: f}, or the exponential notation with {: e}: quantity - 33.45 print ("{:f}".format(quantity)) # 33.450000 print("{:1.If} format(quantity)) #33.5 print ("{:.2e}".format(quantity)) # 3.35e+01
  • 42. 111.5 Exercises In this example the name of the object which gets its value inserted is given as argument to the format method. The first {} pair is replaced by the first argument, the following pairs by the subsequent arguments. Alternatively, it may also be convenient to use the key-value syntax instead: print("{name} {value:.If}".format(name="quantity",value= quantity)) # "quantity 33.5" Here, two values are processed, a string name without a format specifier and a float value which is printed in fixed point notation with one digit after the decimal point. Remark: Braces in the string Sometimes a string might contain a pair of curly braces, which should not be considered as placeholders for a format method. In that case double braces are used: "we {} in LaTeX begin{{equation}}format('like' ) This returns the string 'we like in LaTeX begin{equation}' We refer to the complete reference documentation for more details on string format- ting, [37]. 111.5 Exercises Exercise 1. Check whether x = 2.3 is a zero of the function: fix) = x2 + 0.25x - 5 Exercise 2. According to de Moivre's formula, the following holds: (cos x + i sin x)" = cos nx + i sin nx « e Z, x e R. Choose numbers n and x and verify that formula in Python. Exercise 3. Verify in the same way Euler's formula: e'-* = cosx + isinx x € K. Exercise 4. Suppose that we are trying to check the convergence of a diverging sequence (here the sequence is defined by the recursion relation »„+1 = 2un and uq = 1.0): u=1.0 # you have to use a float here! uold=10. for iteration in xrange(2000): if not abs(u-uold) > l.e-8: print('Convergence') break # sequence has converged uold=u u=2*u else: print('No convergence')
  • 43. Chapter III Variables and Basic Types (a) Since the sequence does not converge, the code should print the "No convergence" message. Execute it to see what happens. (b) What happens if you replace the line if not abs(u-uold) > l.e-8 if abs(u-uold) < l.e-8 It should give exactly the same result, shouldn't it? Run the code again to see what happens. (c) What happens if you replace u = 1. by u = 1 (without decimal point). Run the code to check your predictions. (d) Explain the unexpected behavior of this code. The key to understand what happens is that inf - inf evaluates to nan, and the comparison of nan with anything is always False. Exercise 5. An implication C = (A =?• B) is a Boolean expression which is defined as • C is True if A is False or A and B are both True, • C is False otherwise. Write a Python function implication (a, b). Exercise 6. This exercise is to train Boolean operations. Two binary digits (bits) are added by using a logical device called a halfadder. It produces a carry bit (the digit of next higher value) and the sum as defined by Table III.3, see also Figure III.2. A full adder consists of two half adders and sums up two bits and an additional carry bit on the input, see Figure III.3. by Table 111.3 Definition of the half-adder operation p q sum carry 1 1 0 0 1 0 1 0 0 1 1 0 1 0 0 0 p sum q carry Figure 111.2 A half adder circuit
  • 44. 111.5 Exercises carry in A B HALF ADDER sum carry out HALF ADDER sum carry out OR carry in sum A FULL ADDER B carry out Figure 111.3 A full adder circuit Write a function which implements a half adder and another which implements a full adder. Test these functions.
  • 45. CHAPTER IV Container Types Container types are used to group objects together. The main difference between the dif- ferent container types is the way the individual elements are accessed and how operations are defined. IV. 1 Lists A list is, as the name hints, a list of objects of any kind. L = 'a', 20.0, 5 J M = [3,['a', -3.0, 5]] The individual objects are enumerated by assigning each element an index. The first element in the list gets the index 0. This zero-based indexing is frequently used in mathe- matical notation1 . The index allows access to these objects L[1] # returns 20.0 L[0] # returns 'a' M [ 1 ] # returns ['a',-3.0,5] M[l][2] # returns 5 The bracket notation here corresponds to the use of subscripts in mathematical formulas. l is a simple list, while m itself contains a list, so that one needs two indexes to access an element of the inner list. A list containing subsequent integers can be easily generated by the command range: L=range(4) # generates a list with four elements: [0, 1, 2 ,3] A more general use is to provide this command with start, stop and stride parameters L=range(17,29,4) # generates [17, 21, 25] 'Consider the usual indexing of coefficients of a polynomial.
  • 46. IV.1 Lists 31 The command len returns the length of the list len(L) # returns 3 IV.1.1 Slicing Slicing a list between i and / creates a new list containing the element starting at index / and ending just before j. For slicing a range of indexes has to be given: The l [ i: j ] means: create a list by taking all elements from L starting at L [i] until L [ j -1]. In other words the new list is obtained by removing the first i elements from L and taking the next j - i elements (for j > i > 0). See Figure IV. 1 for more examples. L = ['C, '1', 'o', 'u', 'd','s'] L[l:5] # remove one element and take three from there: # returns I'l', 'o', 'uV'd'J L[2:5] 0 1 2 3 4 5 -1 L[2:] 0 1 2 3 -3 -2 -1 L [: 2] 0 1 2 3 -3 -2 L[2:-l] 0 1 2 3 -3 -2 -1 L [-4:-1] 0 1 -5 -4 -3 -2 L[:-2] 0 1 2 3 -3 -2 -1 L[-2:] 0 1 2 3 -3 Li J Figure IV.1 Some typical slicing situations. Note the syntax: l [i: ] means "remove the / first elements", l [: i] means "take only the first / elements", and, similarly, l [: - i] means "remove the last / elements" and l [-i: ] means "take only the last; elements". This may be combined in L[i: -j ], to remove the first / and the last j elements.
  • 47. Chapter IV Container Types One may omit the first or last bound of the slicing: L = ['C, '1', 'o', 'u','d', 's'] L[l:] # ['1', 'o', 'u', 'd','s'] L [ : 5 ] # ['C , '1 ', 'o', 'W , 'd ' ] L[:] # the entire list Python allows the use of negative indexes for counting from the right. In particular, the element l [ -1 ] is the last element in the list l. • l [ - i; ] amounts to take the last i elements • l [: - i] amounts to take all elements except the / last ones Here is an example: L = ['C, '1', 'o', 'u','d', 's'] L [-2 : ] # ['d', 's'] L [ : -2 ] # ['C , '1 ', 'o', ' u ' ] Mathematical Analogy: Half-Intervals Omitting one index in the range corresponds to half lines in R. The half-open interval (-oo, a) means: take all numbers strictly lower than a; this is similar to the syntax l [: j ]. Remark: Out of bound slices Take notice that you never get index errors with out of bound slices. Possibly, you may obtain empty lists. L = range (4) # [0, 1, 2, 3] L[4] # error! L [1:100] # same as L[1:] L[-100:-l] # same as L[:-l] L[-100:100] # same as L[:] L[5:0] # empty L [-2 : 2] # empty Caution: Variable indexing that becomes negative Be careful when using variables in indexing that may become negative, since it changes the slice completely. This might lead to unexpected results: a = [1,2,3] for iteration in range(4): print(sum(a[0:iteration-1])) The result is 3, 0,1, 3 while one expects 0,0,1,3.
  • 48. IV.1 Lists Strides When computing slices one may also specify a stride which is the length of the step from one index to the other. The default stride is one. L = range(100) L[:10:2] # [0, 2, 4, 6, 8] L [ : : 20] # [0, 20, 40, 60, 80] L [ 10 : 20 : 3 ] # [10, 13, 16, 19] Note that the stride may also be negative: L [20 :10 : -3 ] # [20, 17, 14, 11 It is also possible to create a new list which is reversed, using a negative stride: L = [1, 2, 3] R = L[::-1] # L is not modified R # [3, 2, 1] see also reverse in § IV. 1.4. IV.1.2 Altering lists Typical operations on lists are insertion and deletion of elements and list concatenation. With the slicing notation, list insertion and deletion becomes obvious: Deletion is just replacing a part of a list by an empty list [ ]: L = ['a', 1, 2, 3, 4] L 2:3] = [] # ['a', 1, 3, 4] L 3:] = [ # ['a', 1, 3] Insertion is replacing an empty slice by the list to be inserted: L [ 1:1] = [1000, 2000] # ['a', 1000, 2000, 1, 3] Two lists are concatenated by the "plus" operator: L = [1, -17] M = [-23.5, 18.3, 5.0] L+M # gives [1, -17, 23.5, 18.3, 5.0] Concatenating a list n times with itself motivates the use of the "multiplication" operator: n = 3 n* [1.,17,3] # gives [1. , 17, 3, 1., 17, 3, 1., 17, 3] [ 0 ] * 5 # gi ves [0,0,0,0,0] There exist no arithmetic operations on lists, like element-wise summation or division. For this we refer to arrays, see § IV.2.
  • 49. Chapter IV Container Types IV.1.3 Belonging to a list One may use the keywords in and not in to determine whether an element belongs to a list (similar to e and ^ in mathematics): L = ['a', 1, 'b'( 2] 'a' in L # True 3 in L # False 4 not in L # True IV. 1.4 List Methods Some useful methods of the list type are collected in Table IV.l. Table IV.1 Methods of the type list. command action list.append(x) list.expand(L) list.insert(i,x) list.remove(x) list.count(x) list.sort() list.reverse() list.pop() add x to the end of the list. expands the list by the elements of the list l. insert x at position i. remove the first item from the list whose value is x. the number of times x appears in the list, sort the items of the list, in place, reverse the elements of the list, in place, removes the last element of the list, in place. There are two ways list methods can act: • they can directly alter the list, i.e. in-place operation • they produce a new object In-place operations All methods which result in a list are in-place operating methods, e.g. the method reverse: L = [1, 2, 3] L.reverse!) # the list L is now reversed L # [3, 2, 1] Caution: Be aware of in-place operations One might be tempted to write L=[3, 4, 4, 5] newL = L.sort() This is correct Python. But it results in a (perhaps) unintended alternation of l and a variable newL having the value None. The reason is that sort operates in-place.
  • 50. IV.1 Lists Here we demonstrate in-place operating methods: L = [0,1,2 ,3 ,4 ] L.append(5) # [0, 1, 2, 3, 4, 5] L.reverse() # [5, 4, 3, 2, 1, 0] L.sort() # [C , , 2, 3, 4, 5] L.remove(0) # [1, 2, 3, 4, 5] L.pop() [1 / 2, 3, 4] L.pop() [1 / 2, 3] L.extend([' a' / / b' , ' c' ] ) [1 , 2, 3, 'a', 'b', 'c'] L is altered. The method count is an example of a method which generates a new object: L.count(2) # returns 1 IV.1.5 Merging Lists - zip A particularly useful function for lists is zip. It merges two given lists into a new list by pairing the elements of the original lists. The result is a list of tuples, see § IV.3: ind = [0,1,2,3,4] color = ["red", "green", "blue", "alpha"] zip(color,ind) # gives [('red', 0), ('green', 1), ('blue', 2), ('alpha', 3)] This example also demonstrates what happens if the lists have different lengths. The length of the zipped list is the shorter length of the two input lists. IV.1.6 List Comprehension A convenient way to build up lists is to use the list comprehension construct, possibly with a condition inside. The syntax of a list comprehension is [<expr> for <variable> in <list>] or more general [<expr> for <variable> in <list> if <condition>] Example IV.1 L = [2, 3, 10, 1, 5] L2 = [x*2 for x in L] # [4, 6, 20, 2, 10] L3 = [x*2 for x in L if 4 < x <= 10] # [20, 10]
  • 51. Chapter IV Container Types It is possible to have several for loops inside a list comprehension: M=[[1,2,3], [4,5,6]] flat - [M[i][j] for i in range(2) for j in range(3)] # [1, 2, 3, 4, 5, 6] This is of particular interest when dealing with arrays, see § IV.2. Remark: The map built-in function It is also possible to use the map function to achieve the same effect. The following two pieces of code produce the same outcome: L = [1,2,3] [x*2 for x in L] # [2,4,6] map(lambda x: x*2, L) # [2,4,6] Note however that the use of map forces one to define a function (here an anonymous function, see § VIII.7). Arguably, the list comprehension version is more readable. Since the map version has no advantage over the list comprehension approach, it is rarely useful. Mathematical Analogy: Set Notation List comprehension is closely related to the mathematical notation for sets. Compare: L2 = {2x; x e L] and L2 = [2*x for x in L] One big difference, though, is that lists are ordered while sets aren't, see § IV.5. IV.2 Arrays The NumPy package offers arrays, which are container structures for manipulating vectors, matrices or even higher order tensors in mathematics. In this section we point out the similarities of arrays and lists. But arrays deserve a broader presentation, which will be given in in Chapter V and Chapter VI. Arrays are constructed from lists by the function array: v = array([l.,2.,3.]) A = array([[l.,2.,3.],[4.,5.,6.]]) To access an element of a vector we need one index, while an element of a matrix is addressed by two indexes v [2 ] # returns 3.0 A [ 1, 2 ] # returns 6.0
  • 52. IV.3 Tuples At a first glance, arrays are similar to lists, but be aware they are different in a funda- mental way: • Access to array data corresponds to that of lists, using square brackets and slices, see § IV.l. They may also be used to alter the array: M = array([[1.,2.],[3.,4.]]) v = array([!., 2., 3.]) v[0] # 1. v[:2] # array ( [1., 2. ]) M[0,1] # 2. v[:2] = [10, 201 # v is now array([10., 20., 3.]) • the number of elements in a vector, or the number of rows of a matrix is obtained by the function len: len(v) # 3 • Arrays store only elements of the same numeric type (usually float or complex but also int), see § V.3.1 • The operations +, *, /, - are all elementwise. dot is used for the scalar product and the corresponding matrix operations. • Unlike lists, there is no append method for arrays. Nevertheless there are special meth- ods to construct arrays by stacking smaller size arrays, see § V.7. A related point is that arrays are not "elastic" as lists: one cannot use slices to change their length. • Vector slices are views, i.e., they may be used to modify the original array, see § VI.l. IV.3 Tuples A tuple is an immutable list. Immutable means that it cannot be modified. A tuple is just a comma separated sequence of objects (a list without brackets). To increase readability one often encloses a tuple in a pair of parentheses: my_tuple =1, 2, 3 # our first tuple my_tuple = (1, 2, 3) # the same my_tuple =1, 2, 3, # again the same len(my_tuple) # 3, same as for lists iny_tuple[0] = 'a' # error! tuples are immutable The comma indicates that the object is a tuple: singleton =1, # note the comma len(singleton) # 1
  • 53. Chapter IV Container Types Tuples are useful when a group of values go together, for example, they are used to return multiple values from functions § VIII.3. One may assign several variables at once by unpacking a list or tuple: a, b = 0, 1 # a gets 0 and b gets 1 a, b = [0, 1] # exactly the same effect (a, b) = 0, 1 # same [a,b] = [0,1] # same thing Remark: The swapping trick Use packing and unpacking to swap the contents of two variables: a, b = b, a To summarize: • Tuples are nothing else than immutable lists with a notation without brackets • In most cases lists may be used instead of tuples • The notation without parenthesis is convenient but dangerous. You should use paren- theses when you are not sure: a, b = b, a # the swap trick; equivalent to: (a, b) = (b, a) # but 1, 2 == 3, 4 # returns (1, False, 4) (1, 2) == (3, 4) # returns False IV.4 Dictionaries Lists, tuples and arrays are ordered sets of objects. The individual objects are inserted, accessed and processed according to their place in the list. On the other hand, dictionaries are unordered sets of pairs. One accesses dictionary data by keys. IV.4.1 Creating and Altering Dictionaries For example, we may create a dictionary containing the data of a rigid body in mechanics as follows: truck_wheel - {'name':'wheel' , 'mass':5.7 , 'Ix' : 2 0 . 0, 'ly':1.,'Iz':17., 'center of mass': [0 . ,0 . ,0.]}
  • 54. IV.4 Dictionaries Individual elements are accessed by their keys: truck_wheel['name'] # returns 'wheel' truck_wheel['mass'] # returns 5.7 and new objects are added to the dictionary by creating a new key: truck_wheel['Ixy'] = 0.0 Dictionaries are also used to provide parameters to a function, see § VIII.2. Keys in a dictionary can be among others: strings, functions, tuples with immutable elements, and classes. Keys cannot be lists or arrays. The command diet generates a dictionary from a list with key/value pairs: truck_wheel = diet([('name','wheel'),('mass',5.7),('Ix',20.0), ('ly',1.), ('Iz',17.), ('center of mass[0.,0.,0.])]) The function zip may come in handy in this context, see § IV. 1.5. IV.4.2 Looping over Dictionaries There are mainly three ways to loop over dictionaries: • by keys: for key in truck_wheel.keys(): print(key) # prints (in any order) 'Ix', ' ly', 'name',... or equivalently, for key in truck_wheel: print (key) # prints (in any order) 'Ix', 'ly', 'name',... • by value for value in truck_wheel.value(): print (value) # prints (in any order) 1.0, 20.0, 17.0, 'wheel', ... • by item, i.e., key/value pairs for item in truck_wheel.items(): print (item) # prints (in any order) ('ly', 1.0), ('Ix', 20.0), ('Iz', 17.0), ('name', 'wheel'), See § XIII.4 for a special dictionary object for file access.
  • 55. Exploring the Variety of Random Documents with Different Content
  • 59. The Project Gutenberg eBook of The Philippines: Past and Present (Volume 2 of 2)
  • 60. This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this ebook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. Title: The Philippines: Past and Present (Volume 2 of 2) Author: Dean C. Worcester Release date: January 26, 2013 [eBook #41918] Most recently updated: October 23, 2024 Language: English Credits: Produced by Jeroen Hellingman and the Online Distributed Proofreading Team at http://www.pgdp.net/ for Project Gutenberg (This book was produced from scanned images of public domain material from the Google Print project.) *** START OF THE PROJECT GUTENBERG EBOOK THE PHILIPPINES: PAST AND PRESENT (VOLUME 2 OF 2) ***
  • 61. The Philippines Past and Present THE MACMILLAN COMPANY NEW YORK · BOSTON · CHICAGO · DALLAS ATLANTA · SAN FRANCISCO MACMILLAN & CO., LIMITED LONDON · BOMBAY · CALCUTTA MELBOURNE THE MACMILLAN CO. OF CANADA, LTD. TORONTO
  • 63. The Metamorphosis of a Bontoc Igorot. Two photographs of a Pít-a-pit, a Bontoc Igorot boy. The second was taken nine years after the first.
  • 64. The Philippines Past and Present By Dean C. Worcester Secretary of the Interior of the Philippine Islands 1901–1913; Member of the Philippine Commission, 1900–1913 Author of “The Philippine Islands and Their People”
  • 65. In Two Volumes — With 128 Plates Volume II New York The Macmillan Company 1914 All rights reserved Copyright, 1914, By THE MACMILLAN COMPANY. Set up and electrotyped. Published February, 1914. Norwood Press J. S. Cushing Co.—Berwick & Smith Co. Norwood, Mass., U. S. A.
  • 68. Vol. II Chapter Page XIX. Education 501 XX. The Exploration of Non-Christian Territory 532 XXI. The Government of Non-Christian Tribes 559 XXII. The Government of Non-Christian Tribes (Continued) 591 XXIII. Corrigenda 637 XXIV. Non-Christian Tribe Problems 660 XXV. Slavery and Peonage 676 XXVI. Murder as a Governmental Agency 730 XXVII. The Philippine Legislature 768 XXVIII. The Picturesque Philippines 792 XXIX. Rod, Shotgun and Rifle 806 XXX. Philippine Lands 829 XXXI. Philippine Forests 846 XXXII. Improved Means of Communication 861 XXXIII. Commercial Possibilities of the Philippines 884 XXXIV. Peace and Prosperity 911 XXXV. Some Results of American Rule 921 XXXVI. Is Philippine Independence now Possible? 933 XXXVII. What Then? 961 Appendix Instructions to the First Philippine Commission 975 Proclamation of the First Philippine Commission 977 Instructions to the Second Philippine Commission 980
  • 69. Past and Present Organization of the Courts of the Philippine Islands 988 Present accepted Estimate of the Non- Christian Population of the Philippines 999 Index 1005
  • 71. Vol. II The Metamorphosis of a Bontoc Igorot Frontispiece Facing page Head-hunters’ Weapons 508 The Three Leading Men in the Funeral Procession of an Ifugao who has lost his Head to the Enemy 516 The Sacred Tree of the Ifugaos 524 Entrance to the Quiangan Schoolhouse 534 An Ifugao School 540 The Sub-provincial Building at Quiangan 546 Ifugao Constabulary Soldiers 554 Bontoc Igorot Head-hunters 562 Bontoc Igorot Women in Banana-leaf Costume 570 A Bontoc Igorot Tug-of-war 578 Bontoc Igorot Boys learning to make Furniture 586 A Conference with Ifugao Chiefs 594 Finished Trail built by Ifugaos 602 Difficult Bit of Rock Work on the Mountain Trail in Benguet 610 A Flying Ferry in Operation 618 A Wild Tingian of Apayao 626 Tingian Girls threshing Rice 634 Typical Manobos 640 An Old Bukidnon Chief 650 Typical Street in a Filipino Town 656 A Typical Bukidnon Village Street 656 A Typical Improved Bukidnon House 664 A Typical Neglected Filipino House 664 Making Friends with the Mandayas 670 A Mandayan Boy 678 A Group of Bagobos 686 Moro Boats coming out to meet the Philippine Commission at Jolo 692
  • 72. Among the Moros 700 A Moro Chief with his Wives and Daughter 706 Lieutenant-Governor Manuel Fortich of Bukidnon 708 Governor Frederick Johnson of Agusan 714 A Typical Peon 722 The Penalty for Loyalty to the United States 728 The Philippine Assembly in Session 738 Señor Sergio Osmeña, Speaker of the Philippine Assembly 742 The Manila Hotel 750 Mayon Volcano 756 The Crater of Taal Volcano 764 A Bit of the Pagsanjan Gorge 772 A Giant Tree Fern 780 Scene on a Bird Island 788 A Day’s Catch 796 After the Hunt 804 Typical Scene at the Edge of a Hardwood Forest 812 A Typical Forest Scene 820 Old-style Road across Lowlands 826 New-style Road across Lowlands 826 Typical Old-style Country Road 836 Typical New-style Country Road 836 A Canga, or Carabao Sledge 844 A New-style Cart, with Broad-tired Wheels, which does not injure the Roads 844 Road Destroyers at Work 852 An Old-style Culvert 858 The Old Way of Crossing a River 868 The New Way of Crossing a River 868 A Typical Old-style Bridge 878 A Typical Reënforced Concrete Bridge 878 A Collapsible Bridge 886 Map: Manila, the Future Distributing Centre for the Far East 888 Preparing Rice Land for Planting 892 Planting Rice 892 A Three-year-old Coffee Bush 902
  • 73. A Ceara Rubber Tree 906 A Typical Cocoanut Grove 918 A Typical Filipino Town 922 A Typical Group of Filipinos 930 A Typical Spanish Mestiza 938 A Strange Couple 946 A Member of the Cabaruan Trinity 946 A Typical Old-style Provincial Government Building 962 A Modern Provincial Government Building 962 A Refuge from the Moros 968 A Possible Office-holder 972
  • 75. The Philippines Past and Present
  • 77. Education No work accomplished since the American occupation is of more fundamental and far- reaching importance than that of the Bureau of Education. In order to appreciate it one must gain some familiarity with the conditions which prevailed in Spanish times. The first evidence of the Spanish governmental attitude toward education in the Philippines is found in a royal edict of March 21, 1634,1 in which Felipe IV orders all archbishops and bishops to take steps for the education of the Filipinos in the Spanish language and in Christian doctrine. That this decree was more honoured in the breach than in the observance is evident from another royal decree of June 20, 1686,2 in which the king reminds civil and religious authorities that the non-observance of the decree of 1634 will be charged against them. Neither of these documents provided for financing the scheme of education ordained, but a decree of December 22, 1792,3 did make financial provision for the establishment of Spanish schools for natives. The salaries of teachers were to be paid from the royal treasury, and deficits were to be made up from the communal properties and treasuries. Although this was the first practical attempt to introduce general native education, there are evidences that individual opportunities were offered to, and embraced by, Filipinos. It is probable, too, that in certain localities the most generous of the Spaniards opened private schools. The College of San José was founded in 1601, the University of Santo Tomás in 1619. Neither made provision for educating natives. They were established for the children of Spaniards only, although both later admitted Filipinos. But in the rules for the short-lived college of San Felipe (1641–1645),4 Corcuera lays down the following: “The college servants shall be of influential Pampango families, and they shall be taught to read and write in the Spanish language, and shall be given clerkships if they show aptitude therefor.” We learn that when the charity school of San Juan de Letran passed under the control of the Dominicans in 1640, native boys were admitted, on payment of fees, to share the advantages offered charitably to Spanish orphans.5 Primary education for Filipinos secured no real foothold until 1863.6 In that year, by royal decree, a school system originally planned for Cuba was extended to the Philippines. It made provision for the beginnings of primary instruction in all municipalities of the islands. A summary7 called forth by a circular of March 1, 1866,
  • 78. gives information with regard to the progress actually made. This summary fixes the number of towns at nine hundred, the number of children attending school at one hundred thirty-five thousand boys and twelve thousand two hundred sixty girls, and the number of schools at sixteen hundred seventy-four, but it gives the number of buildings actually in use for schools as only six hundred forty-one. Instruction in Spanish was not always, or even generally, given. In 1863 provision was also made for the establishment of a normal school at Manila. In 1893,8 forty years later, the actual appropriation for the Normal School was $5525. Fourteen years after the American occupation, the appropriation for the Normal School was $56,476.42, in addition to $224,500 spent for new buildings and furniture.9 In 1892 there were two thousand one hundred seventy-three schools. The attendance of these schools was small and irregular. In 1896, at the outbreak of the insurrection, the Spanish had in operation a public school system which could call upon the Normal School for teachers and also upon such graduates of private schools as cared to undertake the work. Naturally the latter were few. Between 1863 and 1893, the Normal School had enrolled two thousand and one students. This may be contrasted with the number of schools which, under the present régime, prepare the pupils for teaching, as well as for other occupations. Including the students of the Philippine Normal School, the Philippine School of Arts and Trades, the Provincial High and Intermediate Schools, nearly thirty-seven thousand pupils are now following studies which fit them more or less to undertake the work of giving instruction to others. In addition to the Normal School, the Spanish established a Nautical School in 1820, a School of Commercial Accounting and of the French and English Languages in 1839, and an Academy of Drawing and Painting. Their final system of public instruction was not badly planned, but it was never actually put into full operation. From the beginning of the insurrection against Spain in 1896 until the beginning of the insurrection against the United States in 1899, most of the public schools were closed. The schoolhouses were used for barracks, prisons, or hospitals. No attempt was made to keep them in repair, and what scanty equipment they had once possessed was for the most part destroyed or stolen. Between 1899 and 1901, many of these buildings were repaired in towns which were occupied by American soldiers, and the beginnings of a public school system were made by our victorious army. Wherever our flag was raised a public school was soon established, soldiers often serving as teachers, and the moral effect of this upon the Filipinos was very great.
  • 79. The city of Manila was naturally the first place to receive attention. Three weeks after our army entered it on August 13, 1898, seven schools were opened under the supervision of Father W. D. McKinnon, chaplain of the first California Regiment. In June, 1899, Lieutenant George P. Anderson was detailed as city superintendent of schools for Manila, and during the following school year he had an average of forty-five hundred pupils enrolled in the primary schools. Captain Albert Todd was detailed to act as superintendent of schools for the islands, but on May 5, 1900, in anticipation of the transfer of the islands from military to civil government, he gave way to Dr. Fred W. Atkinson, who had been chosen by the Philippine Commission as superintendent of public instruction. This title was changed later to that of director of education. On January 21, 1901, the commission passed Act 74, the basis of the present school law. It provided for the appointment of one thousand American teachers to begin the work of establishing a school system carried on in English. Appointments were made as rapidly as possible. By the end of the year, seven hundred sixty-five American teachers were at work. When provision was made for the appointment of this large number of Americans, it was with the idea that they should act as teachers of English in schools over which there should be Filipino principals, but there was, at that time, no body of Filipino teachers properly prepared to carry on school work, and by force of circumstances, this plan was soon altered. Ten school divisions were established, covering the archipelago. Each was presided over by a division superintendent of schools. The teachers were theoretically subject to his control, but the divisions were so large that it was impossible for him to exercise control very effectively. It is perhaps well that many of the teachers were left free to employ their own ingenuity in meeting local conditions. The school system finally established represents a composite of the recommendations of hundreds of teachers scattered throughout the archipelago, and these recommendations were based on hard-earned experience. One of the first duties of teachers was to begin the training of Filipino assistants. This took form in the organization of so-called aspirante classes, into which the best of the Filipino youth who were old enough to teach, and who had already received some education, were gathered. These aspirante classes were often held side by side with classes in the primary schools first established by American teachers, and by the beginning of the year 1902 some of the brightest pupils were able to assist in primary school work. These classes made possible the establishment of organized primary schools under the control of American teachers with Filipino teachers in the lower
  • 80. grades. Their graduates formed the nuclei of the first secondary schools, which were established in 1903. The difficulties which teachers had to overcome at the outset were numerous. In some of the older and richer towns there were stone or brick schoolhouses more or less fit for occupation. In such cases a small number of old wooden benches and a few square feet of blackboard were usually available. Sometimes there were books provided by the army: Baldwin’s readers in English or in rudely translated vernacular; Frye’s geographies translated into Spanish; and possibly Spanish editions of the history of the United States. This stock was greatly improved during the latter half of 1902, and teachers were furnished books and supplies as rapidly as transportation facilities permitted. In 1901 the number of school divisions was increased to eighteen, and in 1902 to thirty- six, making the school divisions identical with the thirty-six then existing political subdivisions of the islands. The organization of the public school system gradually crystallized and assumed something of the form which it has to-day. Barrio10 schools were opened, and the work of American teachers who were detailed to supervise them was thus greatly increased. The school system took permanent shape in 1903 and 1904. As it now stands it is controlled by the director of education, who is responsible for its conduct. Serving with him, and subject to his control, are an assistant director and a second assistant director. The directors have immediate charge of the general office, which has the following divisions: records, accounting, buildings, property, academic, industrial and publications. Each has a chief who is directly responsible for its work. The islands are now divided into thirty-four school divisions, corresponding, except in two cases, to provinces. Each has its superintendent of schools. The divisions are subdivided into districts, over each of which there is a supervising teacher who is responsible for the conduct of its work. Certain of the intermediate schools are under supervising teachers, while others are directly under division superintendents. The school system to-day extends to the remotest barrios. It is organized and equipped for effective work, and ready to carry out promptly and effectively the policies determined upon by the central office. In each province there is a central provincial school offering intermediate and secondary courses. Only twelve of them now give a full four-year course. Others offer three years, two years or one year of secondary work. There is also a manual training department
  • 81. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com