Computational Mathematics With Python
Computational Mathematics With Python
2015
Python is. . .
I Free and open source
I It is a scripting language - an interpreted not a compiled language
I It is object oriented with modern exception handling, dynamic
typing etc.
I It has plenty of libraries among others the scientific ones: linear
algebra; visualisation tools: plotting, image analysis; differential
equations solving; symbolic computations; statistics ; etc.
I It has possible usages: Scientific computing, scripting, web sites,
text parsing, data mining, ...
Note:
In [ 2 ] :
P∞ 1 π2
Computing ζ(x) = k=1 k x with ζ(2) = 6 gives
In [ 12 ] : import scipy . special
In [ 13 ] : scipy . special . zeta ( 2 . , 1 ) # x = 2
1 . 6449340668482266
In [ 14 ] : pi ** 2 / 6
1 . 6449340668482264
You may also use triple quotes for strings including multiple lines:
""" This is
a long ,
long string """
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 is now referenced by x and by y
del x # we delete one of the references
del y # all references are deleted : the object is
deleted
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.
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
Example
L = [2 , 3 , 10 , 1 , 5 ]
L2 = [ x * 2 for x in L ] # [4 , 6 , 20 , 2 , 10 ]
L3 = [ x * 2 for x in L if 4 < x < = 10 ] # [ 20 , 10 ]
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.
for loop
A for loop allows to loop through a list using an index variable.
This variable takes succesively the values of the elements in the list.
for loop
A for loop allows to loop through a list using an index variable.
This variable takes succesively the values of the elements in the list.
Example
L = [1 , 2 , 10 ]
for s in L :
print ( s * 2 ) # output : 2 4 20
One typical use of the for loop is to repeat a certain task a fixed
number of times:
n = 30
for i in range ( n ) :
do_something # this gets executed n times
For Task 2, one needs to give the code to the Python interpreter
which reads the code and figures out what to do with it.
For writing a larger program, one generally uses a text editor which
can highlight code in a good way.