computational mathematics with python · computational mathematics with python author: numerical...
TRANSCRIPT
Computational Mathematics with PythonUnit 1: Getting Started
Numerical Analysis, Lund UniversityLecturers: Claus Führer, Alexandros Sopasakis
2015
Numerical Analysis, Lund University, 2015 1
Introduction and Motivation
Numerical Analysis, Lund University, 2015 2
Why Python?
Python is. . .I Free and open sourceI It is a scripting language - an interpreted not a compiled languageI 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; differentialequations solving; symbolic computations; statistics ; etc.
I It has possible usages: Scientific computing, scripting, web sites,text parsing, data mining, ...
Numerical Analysis, Lund University, 2015 3
Python vs language XX
Java, C++ Object oriented compiled languages. Very limitedand extremely verbose. Low level compared toPython. Few scientific libraries.
C, FORTRAN Very low level compiled language. Useful in someCPU critical situations.
php, ruby Other interpreted languages. PHP is web oriented.Ruby is as flexible as Python but has no scientificlibrary.
MATLAB Tool for matrix computation that evolved forscientific computing. The scientific library is hugebut it is not a programming language. Commercialproduct, not free.
Numerical Analysis, Lund University, 2015 4
Premisses
I We work with a Python version ≥ 3.0.I We use an IPython shellI We start our programs with the line
from scipy import *
Numerical Analysis, Lund University, 2015 5
Examples
Python may be used in interactive mode(executed in an IPython shell)In [2]: x = 3In [3]: y = 5In [4]: print(x + y)8
Note:In [2]:
is the prompt string of the IPython shell. It counts thestatements. In the more basic Python shell the prompt string is> > > .
Numerical Analysis, Lund University, 2015 6
Examples: Linear Algebra
Let us solve [1 23 4
]· x =
[21
]
In [5]: from scipy. linalg import solveIn [6]: M = array([[1., 2.],
[3., 4.]])In [7]: V = array([2., 1.])In [8]: x = solve(M, V)In [9]: print(x)[-3. 2.5]
Note: A line can be continued on the next line without anycontinuation symbol as long as parantheses or brackets are notclosed.
Numerical Analysis, Lund University, 2015 7
More examples
Computing eiπ and 2100:In [10]: print(exp(1j*pi)) # should return -1(-1+1. 22460635382e -16j)In [11]: print(2 ** 100)1267650600228229401496703205376
Note: Everting following # is treated as a comment.
Computing ζ(x) =∑∞
k=11kx with ζ(2) = π2
6 givesIn [12]: import scipy. specialIn [13]: scipy. special .zeta(2., 1) # x = 21. 6449340668482266In [14]: pi ** 2/61. 6449340668482264
Numerical Analysis, Lund University, 2015 8
Concepts: Datatypes and Variables
Numerical Analysis, Lund University, 2015 9
Numbers
A number may be an integer, a real number or a complex number.The usual operations are
I + and - addition and substractionI * and / multiplication and divisionI ** power
2 ** (2+2) # 161j ** 2 # -1
Numerical Analysis, Lund University, 2015 10
Strings
Strings are “lists” of characters, enclosed by simple or doublequotes:’valid string ’" string with double quotes "
You may also use triple quotes for strings including multiple lines:""" This isa long ,long string """
Numerical Analysis, Lund University, 2015 11
Strings
Strings are “lists” of characters, enclosed by simple or doublequotes:’valid string ’" string with double quotes "
You may also use triple quotes for strings including multiple lines:""" This isa long ,long string """
Numerical Analysis, Lund University, 2015 11
Variable
VariablesA variable is a reference to an object. An object may have severalreferences. One uses the assignment operator = to assign a valueto a variable.
Examplex = [3, 4] # a list object is createdy = x # this object is now referenced by x and by ydel x # we delete one of the referencesdel y # all references are deleted : the object is
deleted
Numerical Analysis, Lund University, 2015 12
Concept: Lists
ListsA Python list is an ordered list of objects, enclosed in squarebrackets. One accesses elements of a list using zero-based indicesinside square brackets.
Numerical Analysis, Lund University, 2015 13
List Examples
ExampleL1 = [1, 2]L1[0] # 1L1[1] # 2L1[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
Numerical Analysis, Lund University, 2015 14
List Utilities
I range(n) can be used to fill list with n elements, startingwith zero:list(range(5)) # [0, 1, 2, 3, 4]
I len(L) gives the length of a list:len([’a’, 1, 2, 34]) # returns 4
I Use append to append an element to a list:L = [’a’, ’b’, ’c’]L[-1] # ’c’L. append (’d’)L # L is now [’a’, ’b’, ’c’, ’d ’]L[-1] # ’d’
Numerical Analysis, Lund University, 2015 15
List Utilities
I range(n) can be used to fill list with n elements, startingwith zero:list(range(5)) # [0, 1, 2, 3, 4]
I len(L) gives the length of a list:len([’a’, 1, 2, 34]) # returns 4
I Use append to append an element to a list:L = [’a’, ’b’, ’c’]L[-1] # ’c’L. append (’d’)L # L is now [’a’, ’b’, ’c’, ’d ’]L[-1] # ’d’
Numerical Analysis, Lund University, 2015 15
List Utilities
I range(n) can be used to fill list with n elements, startingwith zero:list(range(5)) # [0, 1, 2, 3, 4]
I len(L) gives the length of a list:len([’a’, 1, 2, 34]) # returns 4
I Use append to append an element to a list:L = [’a’, ’b’, ’c’]L[-1] # ’c’L. append (’d’)L # L is now [’a’, ’b’, ’c’, ’d ’]L[-1] # ’d’
Numerical Analysis, Lund University, 2015 15
List Comprehension
A convenient way to build up lists is to use the list comprehensionconstruct, possibly with a conditional inside.
DefinitionThe syntax of a list comprehension is[<expr> for < variable > in <list>]
ExampleL = [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]
Numerical Analysis, Lund University, 2015 16
List Comprehension in Mathematics
Mathematical NotationThis is very close to the mathematical notation for sets. Compare:
L2 = {2x; x ∈ L}
andL2 = [2*x for x in L]
One big difference though is that lists are ordered while sets aren’t.
Numerical Analysis, Lund University, 2015 17
Operations on Lists
I Adding two lists concatenates (sammanfogar) them:L1 = [1, 2]L2 = [3, 4]L = L1 + L2 # [1, 2, 3, 4]
I Logically, multiplying a list with an integer concatenates thelist with itself several times: n*L is equivalent toL + L + · · ·+ L︸ ︷︷ ︸
n times
.
L = [1, 2]3 * L # [1, 2, 1, 2, 1, 2]
(To multiply each element by c, we use arrays instead of lists.)
Numerical Analysis, Lund University, 2015 18
Operations on Lists
I Adding two lists concatenates (sammanfogar) them:L1 = [1, 2]L2 = [3, 4]L = L1 + L2 # [1, 2, 3, 4]
I Logically, multiplying a list with an integer concatenates thelist with itself several times: n*L is equivalent toL + L + · · ·+ L︸ ︷︷ ︸
n times
.
L = [1, 2]3 * L # [1, 2, 1, 2, 1, 2]
(To multiply each element by c, we use arrays instead of lists.)
Numerical Analysis, Lund University, 2015 18
for loops
for loopA for loop allows to loop through a list using an index variable.This variable takes succesively the values of the elements in the list.
ExampleL = [1, 2, 10]for s in L:
print(s * 2) # output : 2 4 20
Numerical Analysis, Lund University, 2015 19
for loops
for loopA for loop allows to loop through a list using an index variable.This variable takes succesively the values of the elements in the list.
ExampleL = [1, 2, 10]for s in L:
print(s * 2) # output : 2 4 20
Numerical Analysis, Lund University, 2015 19
Repeating a Task
One typical use of the for loop is to repeat a certain task a fixednumber of times:n = 30for i in range(n):
do_something # this gets executed n times
Numerical Analysis, Lund University, 2015 20
Indentation
The part to be repeated in the for loop has to be properly indented:for elt in my_list :
do_something ()something_else ()etc
print ("loop finished ") # outside the for block
Note: In contrast to other programming languages, the indentationin Python is mandatory.
Many other kinds of Python structures also have to be indented,we will cover this when introducing them.
Numerical Analysis, Lund University, 2015 21
Indentation
The part to be repeated in the for loop has to be properly indented:for elt in my_list :
do_something ()something_else ()etc
print ("loop finished ") # outside the for block
Note: In contrast to other programming languages, the indentationin Python is mandatory.
Many other kinds of Python structures also have to be indented,we will cover this when introducing them.
Numerical Analysis, Lund University, 2015 21
Practical Information
Numerical Analysis, Lund University, 2015 22
How to run a piece of code
There are two phases in Python programming:1. Writing the code2. Executing (running) it
For Task 2, one needs to give the code to the Python interpreterwhich reads the code and figures out what to do with it.
Short snippets of code can be written directly in the interpreterand executed interactively. We use the interpreter IPython whichhas extra features.
For writing a larger program, one generally uses a text editor whichcan highlight code in a good way.
There are also development suites which bundle the interpreter,editor and other things into the same program.
Numerical Analysis, Lund University, 2015 23
Spyder
Example of a development environment, Spyder
Numerical Analysis, Lund University, 2015 24
On our computers
The computers in the computer room should have Python andSpyder installed under Windows.
You should set up Spyder according to the instructions athttp://www.maths.lth.se/na/nahelp/
Numerical Analysis, Lund University, 2015 25
On your computer
To install Python and additional necessary libraries for this course,follow the instructions athttp://www.maths.lth.se/na/nahelp/
Numerical Analysis, Lund University, 2015 26
IPythonIPython is an enhanced Python interpreter.You can launch it as a stand-alone application, but it is alsoembedded in Spyder.Some notes on usage:
I To execute the contents of a file named myscript.py justwrite run myscript in IPython or use the green "run" arrow
in the Spyder toolbar.
I Use the arrow keys to visit previous commandsand
I Use the tabulation key to auto-complete commandsand names
I To get help on an object just type ? after it and then returnI When you want to quit, write exit()
Numerical Analysis, Lund University, 2015 27