Basics
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 1 / 307
Introduction and Motivation Concepts Practical Information
2 Concepts
Basic Types
Variables
Lists
For Loop
3 Practical Information
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 2 / 307
Introduction and Motivation Concepts Practical Information
2 Concepts
Basic Types
Variables
Lists
For Loop
3 Practical Information
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 3 / 307
Introduction and Motivation Concepts Practical Information
Why Python?
Python is. . .
I Free and open source
I It is a scripting language, meaning that it is interpreted
I It is modern: object oriented, exception handling, dynamic typing etc.
I Plenty of libraries, in particular scientific ones: linear algebra;
visualisation tools: plotting, image analysis; differential equations solving;
symbolic computations; statistics ; etc.
I Many possible usages: Scientific computing (of course :-)), scripting, web
sites, text parsing, etc.
I Used by YouTube, Google, NASA, Los Alamos, NSA among others
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 4 / 307
Introduction and Motivation Concepts Practical Information
Python vs language XX
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 5 / 307
Introduction and Motivation Concepts Practical Information
Examples
Python may be used in interactive mode:
>>> x = 3
>>> y = 5
>>> print x + y
8
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 6 / 307
Introduction and Motivation Concepts Practical Information
More examples
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 7 / 307
Introduction and Motivation Concepts Practical Information
Demo
Demo
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 8 / 307
Introduction and Motivation Concepts Practical Information
2 Concepts
Basic Types
Variables
Lists
For Loop
3 Practical Information
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 9 / 307
Introduction and Motivation Concepts Practical Information
Numbers
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 10 / 307
Introduction and Motivation Concepts Practical Information
Strings
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 11 / 307
Introduction and Motivation Concepts Practical Information
Strings
You may also use triple quotes for strings including multiple lines:
""" This is
a long ,
long string """
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 11 / 307
Introduction and Motivation Concepts Practical Information
Concept: Variable
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.
Example
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
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 12 / 307
Introduction and Motivation Concepts Practical Information
Concept: Lists
Lists
A python list is an ordered list of objects, enclosed in square brackets. One
accesses elements of a list using zero-based indices inside square brackets.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 13 / 307
Introduction and Motivation Concepts Practical Information
List Examples
Example
L1 = [1 , 2 ]
L1 [ 0 ] # 1
L1 [ 1 ] # 2
L1 [ 2 ] # raises IndexError
L2 = [ ’a ’ , 1 , [3 , 4 ] ]
L2 [ 0 ] # ’a ’
L2 [ 2 ] [ 0 ] # 3
L2 [ - 1 ] # last element : [3 , 4 ]
L2 [ - 2 ] # second to last : 1
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 14 / 307
Introduction and Motivation Concepts Practical Information
List Utilities
I range(n) creates a list with n elements, starting with zero:
print range ( 5 )
[0 , 1 , 2 , 3 , 4 ]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 15 / 307
Introduction and Motivation Concepts Practical Information
List Utilities
I range(n) creates a list with n elements, starting with zero:
print range ( 5 )
[0 , 1 , 2 , 3 , 4 ]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 15 / 307
Introduction and Motivation Concepts Practical Information
List Utilities
I range(n) creates a list with n elements, starting with zero:
print range ( 5 )
[0 , 1 , 2 , 3 , 4 ]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 15 / 307
Introduction and Motivation Concepts Practical Information
Comprehensive lists
A convenient way to build up lists is to use the comprehensive lists
construct, possibly with a conditional inside.
Definition
The syntax of a comprehensive list is
[ < expr > for < x > in < list > ]
Example
L = [2 , 3 , 10 , 1 , 5 ]
L2 = [ x * 2 for x in L ] # [4 , 6 , 20 , 2 , 10 ]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 16 / 307
Introduction and Motivation Concepts Practical Information
Mathematical Notation
This is very close to the mathematical notation for sets. Compare:
L2 = {2x; x ∈ L}
and
L2 = [ 2 * x for x in L ]
One big difference though is that lists are ordered while sets aren’t.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 17 / 307
Introduction and Motivation Concepts Practical Information
Operations on Lists
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 18 / 307
Introduction and Motivation Concepts Practical Information
Operations on Lists
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 18 / 307
Introduction and Motivation Concepts Practical Information
for loop
A for loop allows to loop through a list using an index variable. This
variable is successively equal to all the elements in the list.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 19 / 307
Introduction and Motivation Concepts Practical Information
for loop
A for loop allows to loop through a list using an index variable. This
variable is successively equal to all the elements in the list.
Example
L = [1 , 2 , 10 ]
for s in L :
print s * 2 ,
# output : 2 4 20
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 19 / 307
Introduction and Motivation Concepts Practical Information
Indentation
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 20 / 307
Introduction and Motivation Concepts Practical Information
Repeating a Task
One typical use of the for loop is to repeat a certain task a fixed number
of time:
n = 30
for i in range ( n ) :
do_something # this gets executed n times
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 21 / 307
Introduction and Motivation Concepts Practical Information
2 Concepts
Basic Types
Variables
Lists
For Loop
3 Practical Information
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 22 / 307
Introduction and Motivation Concepts Practical Information
Python Shell
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 23 / 307
Introduction and Motivation Concepts Practical Information
Executing Scripts
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 24 / 307
Introduction and Motivation Concepts Practical Information
Getting Help
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 25 / 307
Introduction and Motivation Concepts Practical Information
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 26 / 307
If Statement For Loop String Formatting Functions
4 If Statement
5 For Loop
6 String Formatting
7 Functions
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 27 / 307
If Statement For Loop String Formatting Functions
4 If Statement
5 For Loop
6 String Formatting
7 Functions
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 28 / 307
If Statement For Loop String Formatting Functions
Conditional Expressions
Definition
A conditional expression is an expression that may have the value True or
False.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 29 / 307
If Statement For Loop String Formatting Functions
Conditional Expressions
Definition
A conditional expression is an expression that may have the value True or
False.
Some common operators that yield conditional expressions are:
I ==, !=
I <, >, <=, >=
I One combines different boolean values with or and and
I not gives the logical negation of the expression that follows
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 29 / 307
If Statement For Loop String Formatting Functions
Example
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 !
Note in the last example the rules when using not, and, or.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 30 / 307
If Statement For Loop String Formatting Functions
Concept: If statement
Concept: conditional statement
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.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 31 / 307
If Statement For Loop String Formatting Functions
Concept: If statement
Concept: conditional statement
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.
Example
We print the absolute value of x. Mathematically this is defined as x if
x ≥ 0 and −x if x < 0:
x = ... (
if x > = 0 : x if x≥0
print x |x| =
else :
−x else
print - x
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 31 / 307
If Statement For Loop String Formatting Functions
4 If Statement
5 For Loop
6 String Formatting
7 Functions
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 32 / 307
If Statement For Loop String Formatting Functions
break gets out of the for loop even if the list we are iterating is not
exhausted.
for x in x_values :
if x > threshold :
break
print x
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 33 / 307
If Statement For Loop String Formatting Functions
else checks whether the for loop was broken with the break keyword.
for x in x_values :
if x > threshold :
break
else :
print " all the x are below the threshold "
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 34 / 307
If Statement For Loop String Formatting Functions
4 If Statement
5 For Loop
6 String Formatting
7 Functions
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 35 / 307
If Statement For Loop String Formatting Functions
I for integers:
nb_students = 16
print " There are % d students " % nb_students
# There are 16 students
I for reals:
average_grade = 3 . 4
print " Average grade : % f " % average_grade
# Average grade : 3 . 400000
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 36 / 307
If Statement For Loop String Formatting Functions
4 If Statement
5 For Loop
6 String Formatting
7 Functions
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 37 / 307
If Statement For Loop String Formatting Functions
Basics on Functions
Functions are useful to gather similar pieces of code at one place. Consider
the following mathematical function:
x 7→ f (x) := 2x + 1
enthought ®
Anatomy of a Function
Anatomy of a function
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 39 / 307
If Statement For Loop String Formatting Functions
Calling a Function
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 40 / 307
If Statement For Loop String Formatting Functions
Concluding example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 41 / 307
If Statement For Loop String Formatting Functions
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 42 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
8 Slicing
Definitions
Examples
9 Tuples
Definition
Usage
10 Convenient Syntax
Multiple Assignments and Comparisons
Tuples and Functions
11 Function arguments
12 Plotting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 43 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
8 Slicing
Definitions
Examples
9 Tuples
Definition
Usage
10 Convenient Syntax
Multiple Assignments and Comparisons
Tuples and Functions
11 Function arguments
12 Plotting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 44 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Creating sublists
Slicing
Slicing a list between i and j is creating a copy of its element starting
from element at index i and ending just before j.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 45 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Creating sublists
Slicing
Slicing a list between i and j is creating a copy of its element starting
from element at index i and ending just before j.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 45 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Creating sublists
Slicing
Slicing a list between i and j is creating a copy of its element starting
from element at index i and ending just before j.
Example
L = [ ’C ’ , ’l ’ , ’a ’ , ’u ’ , ’s ’]
L [ 1 : 4 ] # remove one element and take three from there :
# [ ’ l ’, ’a ’, ’u ’]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 45 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Partial slicing
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 46 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Partial slicing
Mathematical Analogy
This is similar to half lines in R. [−∞, a) means: take all numbers strictly
lower than a; this is similar to the syntax L[:j].
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 46 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
0 1 2 3 ··· -3 -2 -1
L[2:]
Rule of thumb
Taking all elements from index 2 included amounts to remove the
first two elements
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 47 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
0 1 2 3 ··· -3 -2 -1
L[2:]
Rule of thumb
Taking all elements from index 2 included amounts to remove the
first two elements
0 1 2 3 ··· -3 -2 -1
L[:2]
Rule of thumb
Taking all elements until index 2 excluded amounts to keep only the
first two elements
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 47 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
0 1 2 3 ··· -3 -2 -1
L[:-2]
Rule of thumb
Taking all elements until index -2 excluded amounts to remove the
last two elements
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 48 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
0 1 2 3 ··· -3 -2 -1
L[:-2]
Rule of thumb
Taking all elements until index -2 excluded amounts to remove the
last two elements
0 1 2 3 ··· -3 -2 -1
L[-2:]
Rule of thumb
Taking all elements from index -2 included amounts to keep only the
last two elements
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 48 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
0 1 2 3 ··· -3 -2 -1
L[2:-1]
Rule of thumb
L[i:-j] amounts to remove the first i elements and remove the last
j elements.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 49 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
0 1 2 3 ··· -3 -2 -1
L[2:-1]
Rule of thumb
L[i:-j] amounts to remove the first i elements and remove the last
j elements.
0 1 2 3 4 5 ··· -1
L[2:5]
Rule of thumb
L[i:j] amounts to remove the first i and keep the j − i next ones.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 49 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
0 1 ··· -5 -4 -3 -2 -1
L[-4:-1]
Rule of thumb
L[-i:-j] amounts to remove the last j and keep the i − j preceding
ones.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 50 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
8 Slicing
Definitions
Examples
9 Tuples
Definition
Usage
10 Convenient Syntax
Multiple Assignments and Comparisons
Tuples and Functions
11 Function arguments
12 Plotting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 51 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Tuples
Definition
A tuple is an immutable list. Immutable means that it cannot be modified.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 52 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Tuples
Definition
A tuple is an immutable list. Immutable means that it cannot be modified.
Example
my_tuple = 1 , 2 , 3 # our first tuple !
len ( my_tuple ) # 3 , same as for lists
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 52 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 53 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 53 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Formatting Strings
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 54 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
m , i = argmin ( [1 , 2 , 0 ] ) # m is 0 , i is 2
# or :
min_info = argmin ( [1 , 2 , 0 ] )
min_info [ 0 ] # 0
min_info [ 1 ] # 2
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 55 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
I Tuples are nothing else than immutable lists with a notation without
brackets
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 56 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
I Tuples are nothing else than immutable lists with a notation without
brackets
I In most cases lists may be used instead of tuples
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 56 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
I Tuples are nothing else than immutable lists with a notation without
brackets
I In most cases lists may be used instead of tuples
I The bracket free notation is nice but dangerous, you should use
parenthesis when you are not sure:
a , b = b , a # the swap tricks ; equivalent to :
(a , b ) = (b , a )
# but
1 , 2 = = 3 , 4 # returns (1 , False , 4 )
(1 , 2 ) = = (3 , 4 ) # returns False
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 56 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
8 Slicing
Definitions
Examples
9 Tuples
Definition
Usage
10 Convenient Syntax
Multiple Assignments and Comparisons
Tuples and Functions
11 Function arguments
12 Plotting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 57 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Convenient Notations
I Multiple assignment
a = b = c = 1 # a , b and c get the same value 1
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 58 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Convenient Notations
I Multiple assignment
a = b = c = 1 # a , b and c get the same value 1
I Increment operators
a + = 1 # same as a = a + 1
b * = 1 # same as b = b * 1
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 58 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Convenient Notations
I Multiple assignment
a = b = c = 1 # a , b and c get the same value 1
I Increment operators
a + = 1 # same as a = a + 1
b * = 1 # same as b = b * 1
I Multiple comparisons
a < b < c # same as : a < b and b < c
a = = b = = c # same as : a == b and b == c
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 58 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Function Documentation
Try this out and check the IPython help for that function!
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 59 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Functions are objects like everything else. One may pass functions around
as arguments, change their names and delete them.
def square ( x ) :
""" Return the square of ‘x ‘ """
return x * * 2
square ( 4 ) # 16
sq = square # now sq is the same as square
sq ( 4 ) # 16
del square # ‘ square ‘ doesn ’t exist anymore
print newton ( sq , . 2 ) # passing as argument
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 60 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
8 Slicing
Definitions
Examples
9 Tuples
Definition
Usage
10 Convenient Syntax
Multiple Assignments and Comparisons
Tuples and Functions
11 Function arguments
12 Plotting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 61 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Named Arguments
Definition
The argument of a function may be accessed in any order, provided they
are named.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 62 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 63 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 63 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Default Value
Definition
An argument may be given a default value with the equal sign.
Example
def newton (f , x0 , tol = 1e - 6 ) :
...
# the tolerance is set to the default 1e - 6
newton ( cos , . 2 )
newton ( x0 = .2 , f = cos ) # the same as above
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 64 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
8 Slicing
Definitions
Examples
9 Tuples
Definition
Usage
10 Convenient Syntax
Multiple Assignments and Comparisons
Tuples and Functions
11 Function arguments
12 Plotting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 65 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Plot
I You have already used the command plot. It needs a list of x values
and a list of y values. If a single list is given, the list of x values
range(len(y)) is assumed.
I You may use the keyword argument label to give your curves a
name, and then show them using legend.
x = .2
x1 = [ sin (. 3 * n * x ) for n in range ( 20 ) ]
x2 = [ sin ( 2 * n * x ) for n in range ( 20 ) ]
plot ( x1 , label = ’0 . 3 ’)
plot ( x2 , label = ’2 ’)
legend ()
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 66 / 307
Slicing Tuples Convenient Syntax Function arguments Plotting
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 67 / 307
Exceptions Generators Slices Freezing Parameters
13 Exceptions
14 Generators
15 More on slices
16 Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 68 / 307
Exceptions Generators Slices Freezing Parameters
13 Exceptions
14 Generators
15 More on slices
16 Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 69 / 307
Exceptions Generators Slices Freezing Parameters
Creating errors
Creating an error is called “raise an exception”. You may raise an
exception like this:
raise Exception ( " Something went wrong " )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 70 / 307
Exceptions Generators Slices Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 71 / 307
Exceptions Generators Slices Freezing Parameters
Flow Control
An exception stops the flow and looks for the closest enclosing try block.
If it is not caught it continues searching for the next try block.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 71 / 307
Exceptions Generators Slices Freezing Parameters
Error messages
Golden rule
Never print error messages, raise an exception instead
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 72 / 307
Exceptions Generators Slices Freezing Parameters
Error messages
Golden rule
Never print error messages, raise an exception instead
def factorial ( n ) :
if n < 0 :
raise ValueError ( " A positive integer is expected " )
...
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 72 / 307
Exceptions Generators Slices Freezing Parameters
13 Exceptions
14 Generators
15 More on slices
16 Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 73 / 307
Exceptions Generators Slices Freezing Parameters
Definition
Definition
A generator generates objects (to be passed to a for loop). Similar to a list
except that the objects need not exist before entering the loop.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 74 / 307
Exceptions Generators Slices Freezing Parameters
Definition
Definition
A generator generates objects (to be passed to a for loop). Similar to a list
except that the objects need not exist before entering the loop.
Example
A typical generator is xrange: works like range but produces a generator
instead of a sequence.
for i in xrange ( 100000000 ) :
if i > 10 :
break
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 74 / 307
Exceptions Generators Slices Freezing Parameters
Definition
Definition
A generator generates objects (to be passed to a for loop). Similar to a list
except that the objects need not exist before entering the loop.
Example
A typical generator is xrange: works like range but produces a generator
instead of a sequence.
for i in xrange ( 100000000 ) :
if i > 10 :
break
Infinite
Note that, just as in mathematics, generators may be infinite.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 74 / 307
Exceptions Generators Slices Freezing Parameters
Create Generators
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 75 / 307
Exceptions Generators Slices Freezing Parameters
Create Generators
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 75 / 307
Exceptions Generators Slices Freezing Parameters
Generator Tools
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 76 / 307
Exceptions Generators Slices Freezing Parameters
Generator Tools
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 76 / 307
Exceptions Generators Slices Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 77 / 307
Exceptions Generators Slices Freezing Parameters
use instead:
L = [ function ( k ) for k in xrange ( n ) ]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 77 / 307
Exceptions Generators Slices Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 78 / 307
Exceptions Generators Slices Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 78 / 307
Exceptions Generators Slices Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 78 / 307
Exceptions Generators Slices Freezing Parameters
L = list ( g )
# now L is a list with 10 elements
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 79 / 307
Exceptions Generators Slices Freezing Parameters
“Comprehensive” generator
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 80 / 307
Exceptions Generators Slices Freezing Parameters
Zipping generators
for x , y in zip ( xg , yg ) :
print x , y
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 81 / 307
Exceptions Generators Slices Freezing Parameters
Zipping generators
for x , y in zip ( xg , yg ) :
print x , y
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 81 / 307
Exceptions Generators Slices Freezing Parameters
13 Exceptions
14 Generators
15 More on slices
16 Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 82 / 307
Exceptions Generators Slices Freezing Parameters
Out-of-bound slices
Example
L = range ( 4 ) # [0 , 1 , 2 , 3 ]
L [ 4 ] # error !
L [ 1 : 100 ] # same as L [ 1 :]
L [ - 100 : - 1 ] # same as L [: - 1 ]
L [ - 100 : 100 ] # same as L [:]
L [ 5 : 0 ] # empty
L [ - 2 : 2 ] # empty WHY ?
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 83 / 307
Exceptions Generators Slices Freezing Parameters
Altering lists
I Replacement or Deletion
L [ 2 : 3 ] = [ 100 , 200 ] # [ ’ a ’, 1 , 100 , 200 , 3 , 4 ]
L [ 2 : 3 ] = [ ] # [ ’ a ’, 1 , 200 , 3 , 4 ]
L [ 3 : ] = [ ] # [ ’ a ’, 1 , 200 ]
I Insertion
L [ 1 : 1 ] = [ 1000 , 2000 ] # [ ’ a ’, 1000 , 2000 , 1 , 100 ]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 84 / 307
Exceptions Generators Slices Freezing Parameters
Strides
Definition
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.
Example
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 ]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 85 / 307
Exceptions Generators Slices Freezing Parameters
Belonging to a list
Definition
One may use the keywords in and not in to determine whether an
element belongs to a list (similar to ∈ and ∈
/ in mathematics).
Example
L = [ ’a ’ , 1 , ’b ’ , 2 ]
’a ’ in L # True
3 in L # False
4 not in L # True
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 86 / 307
Exceptions Generators Slices Freezing Parameters
13 Exceptions
14 Generators
15 More on slices
16 Freezing Parameters
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 87 / 307
Exceptions Generators Slices Freezing Parameters
Mathematical View
In mathematics one has the following notation, for two sets A and C :
C A := {functions from A to C }
C A×B ≡ (C A )B ≡ (C B )A
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 88 / 307
Exceptions Generators Slices Freezing Parameters
Mathematical View
In mathematics one has the following notation, for two sets A and C :
C A := {functions from A to C }
C A×B ≡ (C A )B ≡ (C B )A
f : (a, b) 7→ f (a, b) ≡ a 7→ fa
where
fa : b 7→ f (a, b)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 88 / 307
Exceptions Generators Slices Freezing Parameters
Practical example
We want to use the function t 7→ sin(2πωt) for various frequencies ω.
Mathematically we have a function
(ω, t) 7→ sin(2πωt)
sinω : t 7→ sin(2πωt)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 89 / 307
Exceptions Generators Slices Freezing Parameters
Practical example
We want to use the function t 7→ sin(2πωt) for various frequencies ω.
Mathematically we have a function
(ω, t) 7→ sin(2πωt)
sinω : t 7→ sin(2πωt)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 89 / 307
Exceptions Generators Slices Freezing Parameters
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 90 / 307
Vectors Matrices
17 Vectors
Vectors vs Lists
Plotting
Creating and Stacking
18 Matrices
Concept
Linear Algebra
Matrix Slices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 91 / 307
Vectors Matrices
17 Vectors
Vectors vs Lists
Plotting
Creating and Stacking
18 Matrices
Concept
Linear Algebra
Matrix Slices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 92 / 307
Vectors Matrices
Lists are almost like vectors but the operations on list are not the linear
algebra operation.
Definition
An array represents a vector in linear algebra. It is often initialised from a
list or another vector. Operations +, *, /, - are all elementwise. dot is
used for the scalar product.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 93 / 307
Vectors Matrices
Vector usage
Example
vec = array ( [ 1 . , 3 . ] ) # a vector in the plane
2 * vec # array ([ 2 . , 6 .])
vec * vec # array ([ 1 . , 9 .])
vec / 2 # array ([ 0 .5 , 1 . 5 ])
norm ( vec ) # norm
dot ( vec , vec ) # scalar product
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 94 / 307
Vectors Matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 95 / 307
Vectors Matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 95 / 307
Vectors Matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 96 / 307
Vectors Matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 97 / 307
Vectors Matrices
More examples I
3 * v1
3 * v1 + 2 * v2
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 98 / 307
Vectors Matrices
More examples II
# access
v1 [ 0 ] # 1 .
v1 [ 0 ] = 10
# slices
v1 [ : 2 ] # array ([ 10 . , 2 .])
v1 [ : 2 ] = [0 , 1 ] # now v1 == array ([ 0 . , 1 . , 3 .])
v1 [ : 2 ] = [1 ,2 , 3 ] # error !
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 99 / 307
Vectors Matrices
So for example the plot of the sine function between zero and ten will be
obtain by:
plot ( xs , sin ( xs ))
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 100 / 307
Vectors Matrices
Vectorised Functions
Note that not all functions may be applied on vectors. For instance this
one:
def const ( x ) :
return 1
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 101 / 307
Vectors Matrices
Creating vectors
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 102 / 307
Vectors Matrices
Concatenating Vectors
Since the + operation is redefined we need a means to concatenate
vectors. This is where the command hstack comes to help.
hstack([v1,v2,...,vn]) concatenates the vectors v1, v2, . . . , vn.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 103 / 307
Vectors Matrices
Concatenating Vectors
Since the + operation is redefined we need a means to concatenate
vectors. This is where the command hstack comes to help.
hstack([v1,v2,...,vn]) concatenates the vectors v1, v2, . . . , vn.
Symplectic permutation
We have a vector of size 2n. We want to permute the first half with the
second half of the vector with sign change:
def symp ( v ) :
n = len ( v ) / / 2 # use the integer division //
return hstack ( [ - v [ - n : ] , v [ : n ] ] )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 103 / 307
Vectors Matrices
17 Vectors
Vectors vs Lists
Plotting
Creating and Stacking
18 Matrices
Concept
Linear Algebra
Matrix Slices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 104 / 307
Vectors Matrices
Definition
Matrices are represented by arrays of lists of rows, which are lists as well.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 105 / 307
Vectors Matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 106 / 307
Vectors Matrices
Creating Matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 107 / 307
Vectors Matrices
Shape
V = array ( [ 1 . , 2 . , 1 . , 4 . ] )
V . shape # (4 ,) <- tuple with one element
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 108 / 307
Vectors Matrices
Transpose
You may switch the two shape elements by transposing the matrix. The
transpose of a matrix Aĳ is a matrix B such that
Bĳ = Aji
A = ...
A . shape # 3 , 4
B = A . T # A transpose
B . shape # 4 , 3
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 109 / 307
Vectors Matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 110 / 307
Vectors Matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 111 / 307
Vectors Matrices
A = array ( [ [ 1 . , 2 . ] ,
[3., 4.]])
b = array ( [ 1 . , 4 . ] )
x = solve (A , b )
dot (A , x ) # should be almost b
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 111 / 307
Vectors Matrices
Slices
Slices are similar to that of lists and vectors except that there are now two
dimensions.
M[i,:] a vector filled by the row i of M
M[:,j] a vector filled by the column j of M
M[2:4,:] slice 2:4 on the lines only
M[2:4,1:4] slice on lines and columns
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 112 / 307
Vectors Matrices
Slices
Slices are similar to that of lists and vectors except that there are now two
dimensions.
M[i,:] a vector filled by the row i of M
M[:,j] a vector filled by the column j of M
M[2:4,:] slice 2:4 on the lines only
M[2:4,1:4] slice on lines and columns
Omitting a dimension
If you omit an index or a slice, SciPy assumes you are taking rows only.
M[3] is the third row of M
M[1:3] is a matrix with the second and third rows of M .
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 112 / 307
Vectors Matrices
Altering a Matrix
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 113 / 307
Vectors Matrices
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 114 / 307
Matrices and Vectors Other Types
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 115 / 307
Matrices and Vectors Other Types
20 Other Types
None
Complex Numbers
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 116 / 307
Matrices and Vectors Other Types
20 Other Types
None
Complex Numbers
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 117 / 307
Matrices and Vectors Other Types
Dot multiplication
vector vector X
s= xi yi
i
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 118 / 307
Matrices and Vectors Other Types
Dot multiplication
vector vector X
s= xi yi
i
matrix vector X
yi = Aĳ xj
j
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 118 / 307
Matrices and Vectors Other Types
Dot multiplication
vector vector X
s= xi yi
i
matrix vector X
yi = Aĳ xj
j
matrix matrix X
Cĳ = Aik Bkj
k
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 118 / 307
Matrices and Vectors Other Types
Dot multiplication
vector vector X
s= xi yi
i
matrix vector X
yi = Aĳ xj
j
matrix matrix X
Cĳ = Aik Bkj
k
vector matrix X
yj = xi Aĳ
i
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 118 / 307
Matrices and Vectors Other Types
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 119 / 307
Matrices and Vectors Other Types
Example
8 9 10 11
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 119 / 307
Matrices and Vectors Other Types
Example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 119 / 307
Matrices and Vectors Other Types
Example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 119 / 307
Matrices and Vectors Other Types
Example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 119 / 307
Matrices and Vectors Other Types
Example
Reshaping
From a given tensor (vector or matrix) one may obtain another tensor by
reshaping.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 120 / 307
Matrices and Vectors Other Types
Reshaping Example
A = arange ( 6 )
0 1 2 3 4 5
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 121 / 307
Matrices and Vectors Other Types
Reshaping Example
A . reshape (1 , 6 )
0 1 2 3 4 5
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 121 / 307
Matrices and Vectors Other Types
Reshaping Example
2
A . reshape (6 , 1 )
3
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 121 / 307
Matrices and Vectors Other Types
Reshaping Example
0 1 2
A . reshape (2 , 3 )
3 4 5
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 121 / 307
Matrices and Vectors Other Types
Reshaping Example
0 1
A . reshape (3 , 2 ) 2 3
4 5
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 121 / 307
Matrices and Vectors Other Types
Reshaping Trick
Note that python can guess one of the new dimensions. Just give a
negative integer for the dimension to be guessed:
A = arange ( 12 ) # a vector of length 12
A . reshape (3 , - 1 ) # 3 , 4 matrix
A . reshape ( -1 , 4 ) # same
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 122 / 307
Matrices and Vectors Other Types
Building Matrices
I Piling vectors
I Stacking vectors
I Stacking column matrices
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 123 / 307
Matrices and Vectors Other Types
Building Matrices
I Piling vectors
I Stacking vectors
I Stacking column matrices
The universal method to build matrices is concatenate. This function is
called by several convenient functions
I hstack to stack matrices horizontally
I vstack to stack matrices vertically
I column_stack to stack vectors in columns
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 123 / 307
Matrices and Vectors Other Types
Stacking Vectors
v1 = array ( [1 , 2 ] )
v2 = array ( [3 , 4 ] )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 124 / 307
Matrices and Vectors Other Types
Stacking Vectors
v1 = array ( [1 , 2 ] )
v2 = array ( [3 , 4 ] ) 1 2
3 4
vstack ( [ v1 , v2 ] )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 124 / 307
Matrices and Vectors Other Types
Stacking Vectors
v1 = array ( [1 , 2 ] )
v2 = array ( [3 , 4 ] ) 1 3
2 4
column_stack ( [ v1 , v2 ] )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 124 / 307
Matrices and Vectors Other Types
Example
You may perform a number of
operations on arrays, either on 1 2 3 4
the whole array, or
column-wise or row-wise. The 5 6 7 8
most common are
I max A . sum ()
I min 36
I sum
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 125 / 307
Matrices and Vectors Other Types
Example
You may perform a number of
operations on arrays, either on 1 2 3 4
the whole array, or
column-wise or row-wise. The 5 6 7 8
most common are
I max A . sum ( axis = 0 )
I min The result is a vector
I sum
6 8 10 12
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 125 / 307
Matrices and Vectors Other Types
Example
You may perform a number of
operations on arrays, either on 1 2 3 4
the whole array, or
column-wise or row-wise. The 5 6 7 8
most common are
I max A . sum ( axis = 1 )
I min The result is a vector
I sum
10 26
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 125 / 307
Matrices and Vectors Other Types
20 Other Types
None
Complex Numbers
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 126 / 307
Matrices and Vectors Other Types
None
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 127 / 307
Matrices and Vectors Other Types
None
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 127 / 307
Matrices and Vectors Other Types
None
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 127 / 307
Matrices and Vectors Other Types
Complex Numbers
Complex numbers are as easy to handle as real numbers. Just use the
syntax <number>j to refer to an imaginary number.
I = 1j
I * * 2 # -1
abs ( I ) # 1
I * ( 1 + I ) # -1 + i
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 128 / 307
Matrices and Vectors Other Types
Complex Numbers
Complex numbers are as easy to handle as real numbers. Just use the
syntax <number>j to refer to an imaginary number.
I = 1j
I * * 2 # -1
abs ( I ) # 1
I * ( 1 + I ) # -1 + i
The real and imaginary parts of a complex number are given by the real
and imag properties
z = ( 1 + 1j ) * * 2
z . real # 0
z . imag # 2
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 128 / 307
Matrices and Vectors Other Types
Complex Numbers
Complex numbers are as easy to handle as real numbers. Just use the
syntax <number>j to refer to an imaginary number.
I = 1j
I * * 2 # -1
abs ( I ) # 1
I * ( 1 + I ) # -1 + i
The real and imaginary parts of a complex number are given by the real
and imag properties or with the numpy function real and imag for arrays
only.
zs = array ( [ 1 . , 3 . ] ) +
z = ( 1 + 1j ) * * 2
1j * array ( [ 2 . , 4 . ] )
z . real # 0
real ( zs ) # array ([ 1 . , 3 .])
z . imag # 2
imag ( zs ) # array ([ 2 . , 4 .])
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 128 / 307
Matrices and Vectors Other Types
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 129 / 307
Booleans Recursion File Handling
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 130 / 307
Booleans Recursion File Handling
Modules
21 Booleans
22 Recursion
23 File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 131 / 307
Booleans Recursion File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 132 / 307
Booleans Recursion File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 132 / 307
Booleans Recursion File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 132 / 307
Booleans Recursion File Handling
Modules
21 Booleans
22 Recursion
23 File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 134 / 307
Booleans Recursion File Handling
Boolean casting
Definition
Using an if statement with a non-boolean type casts it to a boolean. The
rules are as follow:
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 135 / 307
Booleans Recursion File Handling
Boolean casting
Definition
Using an if statement with a non-boolean type casts it to a boolean. The
rules are as follow:
Notice that almost all types will be silently cast to booleans except arrays.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 135 / 307
Booleans Recursion File Handling
Examples
Empty list test
# L is a list
if L :
print " list not empty "
else :
print " list is empty "
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 136 / 307
Booleans Recursion File Handling
Examples
Empty list test
# L is a list
if L :
print " list not empty "
else :
print " list is empty "
Parity test
# n is an integer
if n % 2 :
print " n is odd "
else :
print " n is even "
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 136 / 307
Booleans Recursion File Handling
Modules
21 Booleans
22 Recursion
23 File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 137 / 307
Booleans Recursion File Handling
Avoid Recursion!
Recursion Iteration
def f ( N ) : for i in xrange (
if N = = 0 : return 0 10000000 ) :
return f ( N - 1 ) pass
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 138 / 307
Booleans Recursion File Handling
Avoid Recursion!
Recursion Iteration
def f ( N ) : for i in xrange (
if N = = 0 : return 0 10000000 ) :
return f ( N - 1 ) pass
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 138 / 307
Booleans Recursion File Handling
Modules
21 Booleans
22 Recursion
23 File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 139 / 307
Booleans Recursion File Handling
File I/O
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 140 / 307
Booleans Recursion File Handling
File objects
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 141 / 307
Booleans Recursion File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 142 / 307
Booleans Recursion File Handling
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 142 / 307
Booleans Recursion File Handling
File Modes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 143 / 307
Booleans Recursion File Handling
Module: pickle
you can pickle any python object even code, e.g. functions.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 144 / 307
Booleans Recursion File Handling
Module: pickle
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 145 / 307
Booleans Recursion File Handling
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 146 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
24 Boolean Arrays
Modifying Arrays
Comparing Arrays
25 Iteration
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 147 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
24 Boolean Arrays
Modifying Arrays
Comparing Arrays
25 Iteration
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 148 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Boolean Arrays
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 149 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 150 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 150 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 150 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Comparing Arrays
Note that because array comparison create boolean arrays one cannot
compare arrays directly.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 151 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Comparing Arrays
Note that because array comparison create boolean arrays one cannot
compare arrays directly.
The solution is to use the methods all and any:
A = array ( [ [1 , 2 ] ,[3 , 4 ] ] )
B = array ( [ [1 , 2 ] ,[3 , 3 ] ] )
A = = B # creates array ([[ True , True ] , [ True , False ]])
( A = = B ). all () # False
( A ! = B ). any () # True
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 151 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Boolean Operations
For the same reason as before you cannot use and, or nor not on boolean
arrays! Use the following replacement operators instead:
a and b # error !
a & b # array ([ True , False , False , False ])
a | b # array ([ True , Trues , True , False ])
- a # array ([ False , False , True , True ])
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 152 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
24 Boolean Arrays
Modifying Arrays
Comparing Arrays
25 Iteration
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 153 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Multiple iteration
Comprehensive double for
# M is a matrix
M . shape # (3 , 4 )
flat = [ M [i , j ] for i in range ( M . shape [ 0 ] )
for j in range ( M . shape [ 1 ] ) ]
flat # a list of length 12
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 154 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Multiple iteration
Comprehensive double for
# M is a matrix
M . shape # (3 , 4 )
flat = [ M [i , j ] for i in range ( M . shape [ 0 ] )
for j in range ( M . shape [ 1 ] ) ]
flat # a list of length 12
zip
x_values = [1 , 2 , 3 , 4 ]
y_values = [ 10 , 20 , 30 , 40 ]
for x , y in zip ( x_values , y_values ) :
print " the value at % f is % f " % (x , y )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 154 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
24 Boolean Arrays
Modifying Arrays
Comparing Arrays
25 Iteration
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 155 / 307
Assignment
Boolean Arrays Iteration Objects and References Objects and Types Classes
Variables !""#$%&'%()*+',('")-./'*()+'0'+'%*'"1))
are References
>>> x = [0, 1, 2] x 0 1 2
# y = x cause x and y to point
# at the same list y
>>> y = x
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 156 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Equality vs Identity I
Definition
I Identity is the property of two variables to be the reference to the
same object.
The identity operator is is.
I Equality is the property of two objects to be equal.
The equality operator is ==.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 157 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Equality vs Identity II
Example
To test whether to variables are the same reference you may use is:
L = [ ’a ’ , ’b ’]
L2 = L
L is L2 # True
L2 = [ ’a ’ , ’b ’]
L is L2 # False
L = = L2 # True
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 158 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Copy
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 159 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Copy
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 159 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
24 Boolean Arrays
Modifying Arrays
Comparing Arrays
25 Iteration
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 160 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Type of an object
Each object has a type that may be obtained using the function type.
x = [1 , 2 ] # list
type ( x ) # returns list
y = [2 , 3]
type ( x ) = = type ( y ) # True
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 161 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 162 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Definition
Method and property A method or property is a function bound to an
object. The syntax is
< object > . method ( < arguments ... > )
# or
< object > . property
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 163 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Definition
Method and property A method or property is a function bound to an
object. The syntax is
< object > . method ( < arguments ... > )
# or
< object > . property
I lists: append(<obj>)
I arrays: shape, sum(), max() etc.
I complex: real, imag
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 163 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
24 Boolean Arrays
Modifying Arrays
Comparing Arrays
25 Iteration
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 164 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
We have already seen many types existing in python. For instance, float,
int and complex are types.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 165 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
We have already seen many types existing in python. For instance, float,
int and complex are types.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 165 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 166 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
I object is a keyword
I __init__ is called at the creation of the object
I self is the object itself
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 166 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Usage Example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 167 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Adding methods
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 168 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Adding methods
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 168 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 169 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 170 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 170 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 170 / 307
Boolean Arrays Iteration Objects and References Objects and Types Classes
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 171 / 307
Debugging Operator Overloading
29 Debugging
Motivation
Stack
Debugging Mode
30 Operator Overloading
Operators
Brackets
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 172 / 307
Debugging Operator Overloading
29 Debugging
Motivation
Stack
Debugging Mode
30 Operator Overloading
Operators
Brackets
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 173 / 307
Debugging Operator Overloading
What is a Bug?
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 174 / 307
Debugging Operator Overloading
Bugs in Python
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 175 / 307
Debugging Operator Overloading
Bugs in Python
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 175 / 307
Debugging Operator Overloading
Bugs in Python
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 175 / 307
Debugging Operator Overloading
Bugs in Python
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 175 / 307
Debugging Operator Overloading
The Stack
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 176 / 307
Debugging Operator Overloading
The Stack
Example
def f () :
...
When an exception is raised you see g ()
def g () :
the stack. It is all the functions that
...
called the function where the h ()
exception was raised. def h () :
raise Exception ()
f ()
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 176 / 307
Debugging Operator Overloading
Debugging in IPython
After an exception was raised, enter the debug mode by typing debug.
You are now in debug mode.
You may now inspect the current variables and work as usual.
Demo
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 177 / 307
Debugging Operator Overloading
Debug Commands
h help
q quit
l shows current line
u go up in the stack
d go down in the stack
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 178 / 307
Debugging Operator Overloading
The advantage with that approach is that you may now resume the
execution.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 179 / 307
Debugging Operator Overloading
29 Debugging
Motivation
Stack
Debugging Mode
30 Operator Overloading
Operators
Brackets
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 180 / 307
Debugging Operator Overloading
Operators
Operators (+, *, -, etc.) are defined as methods in python.
operator method
+ __add__
* __mul__
- __sub__
/ __div__
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 181 / 307
Debugging Operator Overloading
Operators
Operators (+, *, -, etc.) are defined as methods in python.
operator method
+ __add__
* __mul__
- __sub__
/ __div__
Example
Given two lists L1 and L2, the following are exactly equivalent:
L = L1 + L2
L = L1 . __add__ ( L2 )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 181 / 307
Debugging Operator Overloading
Redefining Operators
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 182 / 307
Debugging Operator Overloading
Redefining Operators
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 182 / 307
Debugging Operator Overloading
More Operators
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 183 / 307
Debugging Operator Overloading
Brackets
You may also redefine the brackets:
bracket method
() __call__
[] __getitem__
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 184 / 307
Debugging Operator Overloading
Brackets
You may also redefine the brackets:
bracket method
() __call__
[] __getitem__
Example
class polynomial ( object ) :
...
def __call__ ( self , x ) :
return self . eval ( x )
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 185 / 307
Classes vs Functions Attributes Dos and don’t Training 9
31 Classes vs Functions
Problem
Solution
32 Attributes
34 Training 9
Formula
Pieces of Code
Full Code
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 186 / 307
Classes vs Functions Attributes Dos and don’t Training 9
31 Classes vs Functions
Problem
Solution
32 Attributes
34 Training 9
Formula
Pieces of Code
Full Code
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 187 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Functions
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 188 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Functions
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 188 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Functions
A function
I takes an input
I computes, creates local variables
I cleans everything except the output
I returns the output
I ...and dies
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 188 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Output
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 189 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Output
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 189 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Output
Bad solution:
def newton (f , x0 , tol ) :
...
return solution , nb_iterations
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 189 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Output
Bad solution:
def newton (f , x0 , tol ) :
...
return solution , nb_iterations
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 189 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Input
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 190 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Input
Usage:
>>> integrate (f ,0 ,1 ,. 003 , 1e -6 ,...)
< bad result >
>>> integrate (f ,0 ,1 ,. 002 , 1e -6 ,...)
< bad result >
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 190 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Input
Usage:
>>> integrate (f ,0 ,1 ,. 003 , 1e -6 ,...)
< bad result >
>>> integrate (f ,0 ,1 ,. 002 , 1e -6 ,...)
< bad result >
When the function dies, obviously it also forgets everything about the
input arguments!
You have to give the full set of input at every call.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 190 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 191 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Advantages are:
Output Methods return only the essential result, but intermediary
steps are available
Input The inputs are stored and one can modify one part of the
inputs
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 191 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Output
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 192 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Output
Usage:
solver = Newton ( f )
solution = solver . run (. 2 )
# now if I want the number of iterations :
nbIter = solver . nb_iterations
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 192 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Output
Usage:
solver = Newton ( f )
solution = solver . run (. 2 )
# now if I want the number of iterations :
nbIter = solver . nb_iterations
Possible because the the object solver stays alive (although the function
run dies).
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 192 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Example: Input
Usage:
>>> sin_int = Integrator ( sin , 0 , 1 , 1e - 6 )
>>> sin_int . compute ()
< bad result >
>>> sin_int . tol = 1e - 3
>>> sin_int . compute ()
31 Classes vs Functions
Problem
Solution
32 Attributes
34 Training 9
Formula
Pieces of Code
Full Code
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 194 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Methods
Method
A method is a function bound to an object. The syntax is
< object > . method ( < arguments ... > )
# or
< object > . property
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 195 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Methods
Method
A method is a function bound to an object. The syntax is
< object > . method ( < arguments ... > )
# or
< object > . property
For instance:
I list: append(<obj>)
I array: shape, sum(), max() etc.
I complex: real, imag
I Complex: r, i
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 195 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Class attributes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 196 / 307
Classes vs Functions Attributes Dos and don’t Training 9
I You may put any kind of code inside a class statement! This code is
read only once.
class C :
2 + 2 # why not ?
def f ( self ) :
...
g = f # now the method g is added to the class
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 197 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Documentation
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 198 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Debugging
# in the console :
>>> z = Complex (1 , 2 )
>>> print z
1 + 2.i
>>> z
1 + 2.i
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 199 / 307
Classes vs Functions Attributes Dos and don’t Training 9
# this is allowed :
my_sine . derivative = my_cosine
Note that:
I functions, as anything else, are objects
I we added a new attribute to an existing object
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 200 / 307
Classes vs Functions Attributes Dos and don’t Training 9
31 Classes vs Functions
Problem
Solution
32 Attributes
34 Training 9
Formula
Pieces of Code
Full Code
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 201 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Don’t
I No while
I No global
I No map
I No lambda
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 202 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Don’t
I No while
I No global
I No map
I No lambda
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 202 / 307
Classes vs Functions Attributes Dos and don’t Training 9
No While
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 203 / 307
Classes vs Functions Attributes Dos and don’t Training 9
No While
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 203 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Function arguments
A function has access to variables outside their scope. Don’t use this
feature, the outcome is not reliable.
tolerance = 1e - 6
def algorithm () :
...
if abs ( error ) < tolerance # bad !
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 204 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Function arguments
A function has access to variables outside their scope. Don’t use this
feature, the outcome is not reliable.
tolerance = 1e - 6
def algorithm () :
...
if abs ( error ) < tolerance # bad !
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 204 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Errors
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 205 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Errors
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 205 / 307
Classes vs Functions Attributes Dos and don’t Training 9
For loops
Don’t use:
for k in range (...) :
...
element = my_list [ k ]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 206 / 307
Classes vs Functions Attributes Dos and don’t Training 9
For loops
Don’t use:
for k in range (...) :
...
element = my_list [ k ]
or:
for element in my_generator :
No append
Avoid append. It is often used as:
my_list = [ ]
for k in xrange ( n ) :
... # compute some value here
my_list . append ( value )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 207 / 307
Classes vs Functions Attributes Dos and don’t Training 9
No append
Avoid append. It is often used as:
my_list = [ ]
for k in xrange ( n ) :
... # compute some value here
my_list . append ( value )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 207 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 208 / 307
Classes vs Functions Attributes Dos and don’t Training 9
def test_algorithm () :
expected = 3
computed = algorithm (...)
assert expected = = computed
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 208 / 307
Classes vs Functions Attributes Dos and don’t Training 9
31 Classes vs Functions
Problem
Solution
32 Attributes
34 Training 9
Formula
Pieces of Code
Full Code
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 209 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 210 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Then:
∆1 c j−1
cj =
∆j x
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 210 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Then:
∆1 c j−1
cj =
∆j x
How do we program the opertor ∆j in python?
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 210 / 307
Classes vs Functions Attributes Dos and don’t Training 9
∆j
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 211 / 307
Classes vs Functions Attributes Dos and don’t Training 9
∆j
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 211 / 307
Classes vs Functions Attributes Dos and don’t Training 9
∆j
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 211 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 212 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 212 / 307
Classes vs Functions Attributes Dos and don’t Training 9
x = xy [ : ,0 ] # x values
row = xy [ : ,1 ] # first row
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 213 / 307
Classes vs Functions Attributes Dos and don’t Training 9
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 214 / 307
Initial Value Problem
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 215 / 307
Initial Value Problem
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 216 / 307
Initial Value Problem
IVP
The problem:
Find a function u : [t0 , tf ] → Rn with the property
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 217 / 307
Initial Value Problem
Simple Example
The problem
u̇(t) = −3u(t) u(t0 ) = 5
has the solution
u(t) = e−3(t−t0 ) 5
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 218 / 307
Initial Value Problem
Discretisation
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 219 / 307
Initial Value Problem
Euler’s Method
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 220 / 307
Initial Value Problem
U1 = f (ti , ui )
hi hi
U2 = f (ti + , ui + U1 )
2 2
hi hi
U3 = f (ti + , ui + U2 )
2 2
U4 = f (ti + hi , ui + hi U3 )
hi
ui+1 = ui + (U1 + 2U2 + 2U3 + U4 )
6
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 221 / 307
Initial Value Problem
init
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 222 / 307
Initial Value Problem
Class Attributes
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 223 / 307
Initial Value Problem
A dummy method
Some numerical methods use constant step sizes, other variable step sizes.
The change of step sizes is done by a method which is provided here as a
dummy method.
It will be replaced later by something meaningful, when variable stepsizes
are required.
def adjust_step_size ( self )
pass
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 224 / 307
Initial Value Problem
Step generator
We define a method independent step generator
def generator ( self , t , u , tf ) :
"""
Generates the (t , u ) values until t > tf
"""
for i in xrange ( self . max_steps ) :
t , u = self . step (t , u )
if t > tf :
break
yield t , u
self . adjust_stepsize ()
else :
raise Exception (
" Final time not reached within max_steps steps " )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 226 / 307
Initial Value Problem
Postprocessing
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 227 / 307
Initial Value Problem
A method (heritage)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 228 / 307
Initial Value Problem
Another method
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 229 / 307
Initial Value Problem
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 230 / 307
Initial Value Problem
The rhs-function
def my_ode (t , u ) :
return - 3 * u
my_ode . name = " u ’= - 3 * u "
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 231 / 307
Initial Value Problem
Linear Systems
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 232 / 307
Initial Value Problem
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 233 / 307
Performance Broadcasting
36 Performance
37 Broadcasting
Mathematical View
Broadcasting Arrays
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 234 / 307
Performance Broadcasting
36 Performance
37 Broadcasting
Mathematical View
Broadcasting Arrays
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 235 / 307
Performance Broadcasting
What is slow?
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 236 / 307
Performance Broadcasting
Slow/Fast
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 237 / 307
Performance Broadcasting
Vectorization
To improve the performance, one has often to vectorize, i.e., to replace for
loops by numpy functions.
# v is a vector
# we want to shift its values by 5
# slow :
for i in range ( len ( v )) :
v[i] += 5
# fast :
v += 5
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 238 / 307
Performance Broadcasting
36 Performance
37 Broadcasting
Mathematical View
Broadcasting Arrays
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 239 / 307
Performance Broadcasting
Why Broadcasting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 240 / 307
Performance Broadcasting
Why Broadcasting
f → f̄ (t, x) = f (x)
g → ḡ(t, x) = g(t)
and now F = f̄ + ḡ.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 240 / 307
Performance Broadcasting
Simple Example
One of the simplest example of broadcasting in mathematics is constants
being broadcast to function.
If C is a scalar one often writes:
f := sin +C
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 241 / 307
Performance Broadcasting
Simple Example
One of the simplest example of broadcasting in mathematics is constants
being broadcast to function.
If C is a scalar one often writes:
f := sin +C
this is an abuse of notation since one should not be able to add functions
and constants. Constants are however implicitly broadcast to functions:
C̄ (x) := C ∀x
and now
f = sin +C̄
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 241 / 307
Performance Broadcasting
Mechanism
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 242 / 307
Performance Broadcasting
Several Variables
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 243 / 307
Performance Broadcasting
Conventions
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 244 / 307
Performance Broadcasting
Array Broadcasting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 245 / 307
Performance Broadcasting
enthought ®
Array Broadcasting
Example
4x3 4x3
0 1 2 0 0 0 0 1 2 0 0 0
0 1 2 10 10 10 0 1 2 10 10 10
+ = + =
Adding a0 matrix
1 2 20 20 20
of shape 0 1 2
(4,3) and a matrix of20 size
20 20
(1,3). The second
0 1 2 30 30 30 0 1 2 30 30 30
matrix is extended to the shape (4,3).
4x3 3
0 0 0 0 1 2 0 0 0 0 1 2
0 1 2
10 10 10 10 10 10 0 1 2
+ = + = 10 11 12
20 20 20 20 20 20 0 1 2
20 21 22
30 30 30 30 30 30 0 1 2
stretch 30 31 32
4x1 3
0 and T. Oliphant) 0
(Source: E. Jones 1 2 0 0 0 0 1 2
10 10 10 10 0 1 2
+ = + =
20 20 20 20 0 1 2
30 30 30 30 0 1 2
stretch stretch
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 246 / 307
Performance Broadcasting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 247 / 307
Performance Broadcasting
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 247 / 307
Performance Broadcasting
Example
v is a vector of length n
It is to be broadcast to the shape (m, n).
1. v is automatically reshaped to the shape (1, n)
2. v is extended to (m, n)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 248 / 307
Performance Broadcasting
Example
v is a vector of length n
It is to be broadcast to the shape (m, n).
1. v is automatically reshaped to the shape (1, n)
2. v is extended to (m, n)
M = array ( [ [ 11 , 12 , 13 , 14 ] ,
[ 21 , 22 , 23 , 24 ] ,
[ 31 , 32 , 33 , 34 ] ] )
v = array ( [ 100 , 200 , 300 , 400 ] )
M + v # works directly
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 248 / 307
Performance Broadcasting
Example
v is a vector of length n
It is to be broadcast to the shape (m, n).
1. v is automatically reshaped to the shape (1, n)
2. v is extended to (m, n)
M = array ( [ [ 11 , 12 , 13 , 14 ] ,
[ 21 , 22 , 23 , 24 ] ,
[ 31 , 32 , 33 , 34 ] ] )
v = array ( [ 100 , 200 , 300 , 400 ] )
M + v # works directly
Result:
111 212 313 414
121 222 323 424
131 232 333 434
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 248 / 307
Broadcasting Rules
Performance Broadcasting
The trailing axes of both arrays must either be 1 or have the same
Shape Mismatch
size for broadcasting to occur. Otherwise, a “ValueError:
framesa vector
To broadcast are not aligned”
of length exception
n to the shape (n, m)isthe
thrown.
automatic
reshaping will not work.
mismatch!
4x3 4
0 0 0 0 1 2 3
10 10 10
+ =
20 20 20
30 30 30
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 249 / 307
Broadcasting Rules
Performance Broadcasting
The trailing axes of both arrays must either be 1 or have the same
Shape Mismatch
size for broadcasting to occur. Otherwise, a “ValueError:
framesa vector
To broadcast are not aligned”
of length exception
n to the shape (n, m)isthe
thrown.
automatic
reshaping will not work.
mismatch!
4x3 4
0 0 0 0 1 2 3
10 10 10
+ =
20 20 20
30 30 30
M = array ( [ [ 11 , 12 , 13 , 14 ] ,
[ 21 , 22 , 23 , 24 ] ,
[ 31 , 32 , 33 , 34 ] ] )
v = array ( [ 100 , 200 , 300 ] )
M + v # error !
M + v . reshape ( -1 , 1 )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 250 / 307
Performance Broadcasting
M = array ( [ [ 11 , 12 , 13 , 14 ] ,
[ 21 , 22 , 23 , 24 ] ,
[ 31 , 32 , 33 , 34 ] ] )
v = array ( [ 100 , 200 , 300 ] )
M + v # error !
M + v . reshape ( -1 , 1 )
Result:
111 112 113 114
221 222 223 224
331 332 333 334
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 250 / 307
Performance Broadcasting
Typical Examples
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 251 / 307
Performance Broadcasting
Typical Examples
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 251 / 307
Performance Broadcasting
Typical Examples
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 251 / 307
Performance Broadcasting
Typical Examples
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 251 / 307
Performance Broadcasting
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 252 / 307
Modules Dictionaries and Arguments Tests
38 Modules
Imports and run
__main__ variable
40 Tests
What are tests
nosetest
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 253 / 307
Modules Dictionaries and Arguments Tests
38 Modules
Imports and run
__main__ variable
40 Tests
What are tests
nosetest
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 254 / 307
Modules Dictionaries and Arguments Tests
Import
To load the contents of a file you may use import but the file is loaded
only once.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 255 / 307
Modules Dictionaries and Arguments Tests
Import
To load the contents of a file you may use import but the file is loaded
only once.
The various syntax are
I from module import something
I from module import *
I import module
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 255 / 307
Modules Dictionaries and Arguments Tests
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 256 / 307
Modules Dictionaries and Arguments Tests
Typical Example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 257 / 307
Modules Dictionaries and Arguments Tests
Typical Example
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 257 / 307
Modules Dictionaries and Arguments Tests
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 258 / 307
Modules Dictionaries and Arguments Tests
class ...
The tests will be run only when the file is directly run, not when it is
imported.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 259 / 307
Modules Dictionaries and Arguments Tests
38 Modules
Imports and run
__main__ variable
40 Tests
What are tests
nosetest
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 260 / 307
Modules Dictionaries and Arguments Tests
Dictionaries
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 261 / 307
Modules Dictionaries and Arguments Tests
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 262 / 307
Modules Dictionaries and Arguments Tests
One may also use items to loop through keys and values:
for key , value in homework_passed . items () :
print " % s % s " % ( key , value )
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 262 / 307
Modules Dictionaries and Arguments Tests
One may also use items to loop through keys and values:
for key , value in homework_passed . items () :
print " % s % s " % ( key , value )
One may use the keys and values methods to copy or change the
dictionary:
dict_items = zip ( homework_passed . keys () ,
homework_passed . values ())
other_dict = dict ( dict_items ) # same dictionary
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 262 / 307
Modules Dictionaries and Arguments Tests
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 263 / 307
Modules Dictionaries and Arguments Tests
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 264 / 307
Modules Dictionaries and Arguments Tests
One may transform this list into an argument list for positional arguments
with the single star operator:
newton ( L [ 0 ] , L [ 1 ] ) # ok but cumbersome
newton ( * L ) # does the same thing
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 264 / 307
Modules Dictionaries and Arguments Tests
Similarly, if one is given a dictionary one may use for keyword arguments
the double star operator:
D = { ’ x0 ’: .3 , ’f ’: cos }
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 265 / 307
Modules Dictionaries and Arguments Tests
Similarly, if one is given a dictionary one may use for keyword arguments
the double star operator:
D = { ’ x0 ’: .3 , ’f ’: cos }
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 265 / 307
Modules Dictionaries and Arguments Tests
Passing arguments
Also in the definition of functions you might find these constructs. This is
often used to pass parameters through a function
def letssee (f , x , * args , * * keywords ) :
return f (x , * args , * * keywords )
def look (x ,y ,z , u ) :
print y , z
print u
return x * * 2
A call gives
L = [1 , 2 ] 1 2
D = { ’u ’: 15 } 15
letssee ( look ,3 , *L , * * D ) Out [ 35 ] : 9
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 266 / 307
Modules Dictionaries and Arguments Tests
38 Modules
Imports and run
__main__ variable
40 Tests
What are tests
nosetest
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 267 / 307
Modules Dictionaries and Arguments Tests
Why Tests?
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 268 / 307
Modules Dictionaries and Arguments Tests
Why Tests?
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 268 / 307
Modules Dictionaries and Arguments Tests
Automated Tests
Automated tests
I ensure a constant (high) quality standard of your code
I serve as a documentation of the use of your code
I document the test cases → test protocol
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 269 / 307
Modules Dictionaries and Arguments Tests
Example
A matrix property:
Two matrices A,B are called similar, if there excists a matrix S, such that
B = S −1 AS. A and B have the same eigenvalues.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 270 / 307
Modules Dictionaries and Arguments Tests
Example (Cont.)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 271 / 307
Modules Dictionaries and Arguments Tests
Example (Cont.)
even reaction on wrong input should be checked
class test_sim ( object ) :
...
S0 = zeros (( 2 , 2 ))
...
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 272 / 307
Modules Dictionaries and Arguments Tests
nosetests
OK
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 273 / 307
Modules Dictionaries and Arguments Tests
Test Cases
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 274 / 307
Modules Dictionaries and Arguments Tests
Test discovering
nosetest will discover all your test automatically provided the name of
the file/class/function starts with test:
nosetests test_file.py:Test_Similar.test_eigenvalue
nosetests test_file.py:Test_Similar
nosetests test_file.py
or even:
nosetests
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 275 / 307
Modules Dictionaries and Arguments Tests
Testing Tools
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 276 / 307
Modules Dictionaries and Arguments Tests
Advice
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 277 / 307
Modules Dictionaries and Arguments Tests
Advice
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 277 / 307
Modules Dictionaries and Arguments Tests
Spring 2009
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 278 / 307
Matlab for Python users Matlab What we didn’t do in this course
42 Matlab
Syntax
Lists, Dictionaries, Arrays
Linear Algebra
Functions
Environment
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 279 / 307
Matlab for Python users Matlab What we didn’t do in this course
Matlab
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 280 / 307
Matlab for Python users Matlab What we didn’t do in this course
Matlab
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 280 / 307
Matlab for Python users Matlab What we didn’t do in this course
42 Matlab
Syntax
Lists, Dictionaries, Arrays
Linear Algebra
Functions
Environment
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 281 / 307
Matlab for Python users Matlab What we didn’t do in this course
I comments with %
% matlab comment # python comment
if z == 0 if z = = 0 :
dosomething dosomething
else else :
dosomethingelse dosomethingelse
end #
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 282 / 307
Matlab for Python users Matlab What we didn’t do in this course
Type
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 283 / 307
Matlab for Python users Matlab What we didn’t do in this course
Operators
2^3 % 8 2**3 # 8
2 ~= 3 % 1 2 ! = 3 # True
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 284 / 307
Matlab for Python users Matlab What we didn’t do in this course
Printing out
Matlab will always display (echo) what you defined unless you end the
assignment with a semicolon
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 285 / 307
Matlab for Python users Matlab What we didn’t do in this course
Operator differences
I No multiple comparison
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 286 / 307
Matlab for Python users Matlab What we didn’t do in this course
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 287 / 307
Matlab for Python users Matlab What we didn’t do in this course
Creating matrices
The syntax is
M = [1 2 3; 4 5 6]
size ( M ) % 2 3
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 288 / 307
Matlab for Python users Matlab What we didn’t do in this course
Creating matrices
The syntax is
M = [1 2 3; 4 5 6]
size ( M ) % 2 3
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 288 / 307
Matlab for Python users Matlab What we didn’t do in this course
Creating matrices
The syntax is
M = [1 2 3; 4 5 6]
size ( M ) % 2 3
Since you may not create vectors you must store vectors in row or column
matrices.
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 288 / 307
Matlab for Python users Matlab What we didn’t do in this course
Transpose
The single quote is used for transposing matrices (and for delimiting
strings).
s = ’ abc ’
v = [1:3] % row matrix
v ’ % column matrix
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 289 / 307
Matlab for Python users Matlab What we didn’t do in this course
Shapes
s = size ( M ) s = shape ( M )
s (1) % ok s [ 0 ] # ok
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 290 / 307
Matlab for Python users Matlab What we didn’t do in this course
Operators
V = [1 2 3] V = array ( [1 ,2 , 3 ] )
W = [3 4 5] W = array ( [3 ,4 , 5 ] )
V * W % error !
V .* W % ok V * W # ok
V / W % error !
V ./ W % ok V / W # ok
V ^ W % error !
V .^ W % ok V * * W # ok
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 291 / 307
Matlab for Python users Matlab What we didn’t do in this course
Slices
V = [1 2 3] V = array ( [1 , 2 , 3 ] )
V (2: end ) - V (1: end -1) v[1:] - v[:-1]
V (2:) % error ! V [ 1 : ] # ok
V (2:100) % error ! V [ 1 : 100 ] # same as V [ 1 :]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 292 / 307
Matlab for Python users Matlab What we didn’t do in this course
for loops
% right :
c = (1:3) ’
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 293 / 307
Matlab for Python users Matlab What we didn’t do in this course
Functions in Matlab
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 294 / 307
Matlab for Python users Matlab What we didn’t do in this course
Functions in Matlab
Local Functions
I available only in the file they are defined
I must be declared after the main file function
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 294 / 307
Matlab for Python users Matlab What we didn’t do in this course
Functions
For file functions the function name is not used; what is used is the name
of the file instead (similar to shell scripting)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 295 / 307
Matlab for Python users Matlab What we didn’t do in this course
Functions
For file functions the function name is not used; what is used is the name
of the file instead (similar to shell scripting)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 295 / 307
Matlab for Python users Matlab What we didn’t do in this course
function ret = f ()
To return the value one simply sets the variable ret to the value we want
to return.
ret = 2 % the function returns 2
Notice that the execution will continue after this, unless you write return
(but not return 2)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 296 / 307
Matlab for Python users Matlab What we didn’t do in this course
Used as:
r = f
r {1} % 2
r {2} % 3
% but
f {1} % error !
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 297 / 307
Matlab for Python users Matlab What we didn’t do in this course
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 298 / 307
Matlab for Python users Matlab What we didn’t do in this course
feval and @
Functions are not objects so you must use a special symbol to pass it
around.
function [ res ] = fname ( x )
...
end
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 299 / 307
Matlab for Python users Matlab What we didn’t do in this course
feval and @
Functions are not objects so you must use a special symbol to pass it
around.
function [ res ] = fname ( x )
...
end
You can’t pass this function using fname because fname executes the
function! You have to prevent the execution using the @ operator.
f = @fname
% now how to execute the function ?
f(x)
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 299 / 307
Matlab for Python users Matlab What we didn’t do in this course
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 300 / 307
Matlab for Python users Matlab What we didn’t do in this course
Mathematical Functions
Most of the mathematical functions, for computing and plotting, have the
same name in matlab and scipy. Examples are:
I plot, legend, grid, pcolor,. . .
I eig, eigs, svd, qr, . . .
I rand, . . .
I sin, cos, tan,. . .
I det, norm, . . .
I linspace, logspace, roll, . . .
I real, imag, . . .
I sum, max, min, mean, cumsum, cumprod, diff, . . .
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 301 / 307
Matlab for Python users Matlab What we didn’t do in this course
Variables
x = [1 2 3; 4 5 6] x = array ( [ [1 ,2 , 3 ] ,[4 ,5 , 6 ] ] )
y = x y = x
y (1 ,1) = 0 y [0 , 0 ] = 0 # x is changed
x % unchanged x # [[ 0 ,2 , 3 ] ,[4 ,5 , 6 ]]
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 302 / 307
Matlab for Python users Matlab What we didn’t do in this course
Modules
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 303 / 307
Matlab for Python users Matlab What we didn’t do in this course
Exception handling
function a = divideme (b , c )
InfEx = MException ( ’ MATLAB : Inf ’ , ’ division by zero ’ );
a=b/c;
if a == inf def divideme (b , c ) :
throw ( InfEx ) return b / c
end try :
a = divideme (1 , 0 )
try except :
print ’ Division by zero ’
a = divideme (1 ,0)
catch InfEx
disp ( InfEx . message )
end
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 304 / 307
Matlab for Python users Matlab What we didn’t do in this course
License
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 305 / 307
Matlab for Python users Matlab What we didn’t do in this course
42 Matlab
Syntax
Lists, Dictionaries, Arrays
Linear Algebra
Functions
Environment
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 306 / 307
Matlab for Python users Matlab What we didn’t do in this course
Olivier Verdier and Claus Führer Computational Mathematics with Python Spring 2009 307 / 307