Python Shorten

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

Python for Scientific Computing

Introduction
UMR MISTEA Montpellier France

2016

Pascal.Neveu@supagro.inra.fr 1/73

Plan

Introduction.......................... p 3
Python for sciences............... p 11
Structure and types............... p 16
Data manipulations............... p 40
Matrix Operations................. p 50
Exercises.............................. p 78
Practices and performance.... p 59

Pascal.Neveu@supagro.inra.fr 2/73

Introduction
Python:
- Powerful programming language
- Available on different platforms
- Effective approach to object-oriented programming
- Dynamic typing and interpreted
- Easy to learn, (help function) and Web resources
Some Spanish references:
http://es.wikipedia.org/wiki/Python
http://docs.python.org.ar/tutorial/contenido.html
Current versions: 3.3 or 2.7 ( 3.3 vs 2.7?)

Pascal.Neveu@supagro.inra.fr 3/73

Introduction
Invoking python
- Script mode
pn@pn-laptop:~/PYTHON$ cat prog1.py
print 2+3
pn@pn-laptop:~/PYTHON$ python prog1.py
5
- Interactive mode
pn@pn-laptop:~/PYTHON$ python
Python 2.6.5 (r265:79063, Oct 1 2012, 22:04:36)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" ...
>>> 1+2
3
Pascal.Neveu@supagro.inra.fr 4/73

Introduction: list

>>>
>>>
[1,
>>>
1
>>>
3

numbers=[1,2,3]
numbers
2, 3]
numbers[0]
numbers[2]

>>> numbers=array(numbers) # numpy module


>>> help(array)
.......

Pascal.Neveu@supagro.inra.fr 5/73

Introduction: if statement
>>> x=2
>>> if x>1 : x=x+1
...
>>> x
3
>>> if x < 0:
...
x = 0
...
print Negative changed to zero
... elif x == 0:
...
print Zero
... else:
...
print More
...
More
Pascal.Neveu@supagro.inra.fr 6/73

Introduction: for statement

>>> words= [cat,dog,horse]


>>> for w in words:
...
print it is a ,w
...
it is a cat
it is a dog
it is a horse

Pascal.Neveu@supagro.inra.fr 7/73

Introduction: for statement (cont.)

>>> range(3)
[0, 1, 2]
>>> for i in range(3):
...
print i,is a ,words[i]
...
0 is a cat
1 is a dog
2 is a horse

Pascal.Neveu@supagro.inra.fr 8/73

Introduction: while statement

>>> while a>0:


...
print a=,a
...
a=a-1
...
a= 3
a= 2
a= 1

Pascal.Neveu@supagro.inra.fr 9/73

Introduction: function definition

>>> def addFive(n):


...
return(n+5)
...
>>> addFive(3)
8
import or from instructions allow to use modules or packages
A module is a file containing Python definitions and statements
A package is a collection of modules.

Pascal.Neveu@supagro.inra.fr 10/73

Scientific computing with Python

Python + Packages: Numpy / Scipy / Matplotlib


Characteristics:
Free software for scientific computing
Available on Linux, Windows, MacOs,...
A large Community of researchers and engineers
Universal programming language (a lot of functionalities)

Pascal.Neveu@supagro.inra.fr 11/73

Numpy / Scipy / Matplotlib


Pylab: Numpy / Scipy / matplotlib
Web site www.scipy.org
Numpy: vector, matrix and vectorised instructions
Scipy: scientific libraries
Matplotlib: graphic library
SciKits: Scipy extensions (Toolboxes)
Fipy: Partial Differential Equation
IPython: meta-package
Mpmath: high precision

Similar software: Matlab (Commercial), Scilab, Octave, SAGE


http://www.scipy.org/NumPy_for_Matlab_Users
http://mathesaurus.sourceforge.net/matlab-python-xref.pdf
Pascal.Neveu@supagro.inra.fr 12/73

Starting: first way


Explicitly import: needs to use name-spaces
>>> import numpy as np
>>> import scipy as sc
>>> a=3
>>> b=8
>>> max(a,b)
8
>>> np.max(a,b)
3
>>> np.max([a,b])
8

# better to use amax


Pascal.Neveu@supagro.inra.fr 13/73

Starting: second way

>>> from numpy import *


>>> from scipy import *
>>> x=3
>>> y=2
>>> log(x) + 2
3.09861228866811
>>> max(log(x), y)
2
You can inadvertently overriding other functions or objects
Pascal.Neveu@supagro.inra.fr 14/73

Starting: third way


ipython -pylab
In [1]: a=4 ; b=3
In [2]: max(a,b)
Out[2]: 4
In [3]: history -n
a=4 ; b=3
max(a,b)
In [4]: whos
Variable
Type
Data/Info
---------------------------a
int
4
b
int
3
Pascal.Neveu@supagro.inra.fr 15/73

Main data types

bool
int
int8
uint8
float
float16
float32
complex
string

Boolean (True or False)


Platform integer (int32 or int64)
Byte (-128 to 127)
Unsigned integer (0 to 255)
float64 8 bytes.
Half precision 2 bytes
Single precision 4 bytes
complex128 32 bytes
string

http://docs.scipy.org/doc/numpy/user/basics.types.html

Pascal.Neveu@supagro.inra.fr 16/73

Predefined constants

True
False
e
1j
inf
nan
pi

boolean true representation


boolean false representation
e constant
imaginary part of complex number
infinite value representation
not a number (sometime missing value)
constant

Pascal.Neveu@supagro.inra.fr 17/73

Main structures

Scipy provides following structures:


vector: array
matrix: array and matrix
hypermatrix: array
list: list

Pascal.Neveu@supagro.inra.fr 18/73

Matrix and Array


Which one is better?
Array:
array is the standard structure
A*B : element by element product
multidimensional

Matrix:
Matlab behavior
A*B : matrix product
dimension 2 (only)

Pascal.Neveu@supagro.inra.fr 19/73

Vector creating
Unidimensional array (ordering values)
>>> a=array([1,2,3,4])
>>> a
array([1, 2, 3, 4])
>>> size(a)
4
# index from 0
>>> a[2]
3
# select elements 4 and 2
>>> a[[3,1]]
array([4, 2])

Pascal.Neveu@supagro.inra.fr 20/73

Vector creating (cont.)


Column vector
>>> a.reshape(4,1)
array([[1],
[2],
[3],
[4]])
Vectors of character strings
>>> A = array([texte, chaine])
>>> A
array([texte, chaine],
dtype=|S6)
Pascal.Neveu@supagro.inra.fr 21/73

Vector generating
>>> v=r_[1:11]
array([ 1, 2,

3,

4,

5,

6,

7,

8,

9, 10])

>>> v=linspace(0,pi,5)
array([ 0. , 0.7853981, 1.5707963, 2.3561944, 3.1415926])
>>> v=arange(5)
array([0, 1, 2, 3, 4])
>>> v=arange(1,11,3)
array([ 1, 4, 7, 10])
>>> v=arange(1,11,2.5)
array([ 1. , 3.5, 6. ,

8.5])
Pascal.Neveu@supagro.inra.fr 22/73

Vector generating (cont.)


Attention: range and arange functions are differents
>>> a=range(5)
[0, 1, 2, 3, 4]
>>> arange(5)
array([0, 1, 2, 3, 4])
>>> range(5)*2
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
>>> arange(5)*2
array([0, 2, 4, 6, 8])

Pascal.Neveu@supagro.inra.fr 23/73

Matrix creating with array


>>> A=array([[1.,2,3],[4,5,6]])
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
>>> B=array(([1,2,3],[4,5,6]))
array([[1, 2, 3],
[4, 5, 6]])
>>> C=array(([1,2,3],[4,5,6]),int32)
>>> D=array([[1,2,3],[4,5,6]],int16)
>>> whos
Variable
Type
Data/Info
----------------------------A
ndarray
2x3: 6 elems, type
B
ndarray
2x3: 6 elems, type
C
ndarray
2x3: 6 elems, type
D
ndarray
2x3: 6 elems, type

float64, 48 bytes
int64, 48 bytes
int32, 24 bytes
int16, 12 bytes
Pascal.Neveu@supagro.inra.fr 24/73

Matrix creating with mat


>>> A=mat("1 2 3; 4 5 6")
>>> A
matrix([[1, 2, 3],
[4, 5, 6]])
row vector (dimension: 2)
>>> mat("1 2 3")
matrix([[1, 2, 3]])
column vector (dimension: 2)
>>> mat("1;2;3")
matrix([[1],
[2],
[3]])
Pascal.Neveu@supagro.inra.fr 25/73

Matrix creating with mat


>>> A
matrix([[1, 2, 3],
[4, 5, 6]])
>>> A[1,2]
6
>>> A[1]
matrix([[4, 5, 6]])
>>> A[1,:]
matrix([[4, 5, 6]])
>>> A[:,2]
matrix([[3],
[6]])
Pascal.Neveu@supagro.inra.fr 26/73

Matrix generating

Identity matrix: eye(3)


Matrix with 1 elements: ones((2,6))
Matrix with 0 elements: zeros((2,6))
Diagonal matrix: diag((4,5,6))

Pascal.Neveu@supagro.inra.fr 27/73

Matrix generating: vector binding


>>> a=arange(2,11,2)
array([ 2, 4, 6, 8, 10])
>>> b=arange(1,10,2)
array([1, 3, 5, 7, 9])
>>> vstack((a,b))
array([[ 2, 4, 6,
[ 1, 3, 5,
>>> hstack((a,b))
array([ 2, 4, 6,

8, 10],
7, 9]])

8, 10,

1,

3,

5,

7,

9])

Pascal.Neveu@supagro.inra.fr 28/73

Matrix generating: matrix and vector binding


>>> A
array([[1, 2, 3],
[4, 5, 6]])
>>> vstack([A,arange(3)])
array([[1, 2, 3],
[4, 5, 6],
[0, 1, 2]])
>>> hstack((A,A))
array([[ 1., 2.,
[ 4., 5.,

3.,
6.,

1.,
4.,

2.,
5.,

3.],
6.]])

Pascal.Neveu@supagro.inra.fr 29/73

Matrix and vector copy


>>> a=arange(5)
>>> b=a
>>> b[2]=100
# a is also modified
>>> a
array([ 0,
1, 100,

3,

4])

>>> A=mat("1 2 3; 4 5 6")


matrix([[1, 2, 3],
[4, 5, 6]])
>>> B=A
>>> A[0,1]=12

Pascal.Neveu@supagro.inra.fr 30/73

Matrix and vector copy (cont.)


>>> A
matrix([[
[
>>> B
matrix([[
[

1, 12,
4, 5,

3],
6]])

1, 12,
4, 5,

3],
6]])

>>> B=A.copy()
>>> A[0,1] = 3
>>> B
matrix([[ 1, 12,
[ 4, 5,

3],
6]])

Pascal.Neveu@supagro.inra.fr 31/73

Logical operators

==
!=
>
>=
<
<=
~
not
and
or
xor

equal
not equal
greater
greater and equal
lower
lower and equal
not
not
logical and
logical or
exclusive OR

Pascal.Neveu@supagro.inra.fr 32/73

Logical operators (cont.)

Logical arrays: True or False elements


In arithmetic context:
True becomes 1
False becomes 0

Pascal.Neveu@supagro.inra.fr 33/73

Logical array

>>> A
array([[1, 2, 3],
[4, 5, 6]])
>>> A > 2
array([[False, False,
[ True, True,

True],
True]], dtype=bool)

>>> sum(A>2)
4

Pascal.Neveu@supagro.inra.fr 34/73

File writing
In [18]: A=arange(5)
In [19]: savetxt(fichier.txt,A)
# os: operating system interface module
In [20]: import os
In [21]: os.system(cat fichier.txt)
0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
4.000000000000000000e+00
Out[21]: 0
Pascal.Neveu@supagro.inra.fr 35/73

File reading

In [22]: B=loadtxt(fichier.txt)
In [23]: B
Out[23]: array([ 0.,

1.,

2.,

3.,

4.])

In [24]: B=B.astype(int)

Pascal.Neveu@supagro.inra.fr 36/73

Explicit reference
Attention
>>> import numpy as np
>>> A = np.array([[1,2,3],[4,5,6]])
>>> sum(A)
array([5, 7, 9])
>>> np.sum(A)
21

Pascal.Neveu@supagro.inra.fr 37/73

Constant manipulation
>>> sqrt(-1)
1j
>>> A = array([1,nan,2])
>>> A
array([ 1., NaN,
2.])
>>> max(A)
nan
>>> sum(A)
nan
>>> 1/inf
0.0

Pascal.Neveu@supagro.inra.fr 38/73

Constant manipulation (cont.)

Attention:
>>> nan == nan
False
>>> isnan(nan)
True

Pascal.Neveu@supagro.inra.fr 39/73

Manipulations
Data manipulation, two ways:
with index
with logical

Vector manipulations with index


>>> v
array([ 1,

2,

3,

4,

5,

6,

7,

8,

9, 10])

>>> v[:]
array([ 1,

2,

3,

4,

5,

6,

7,

8,

9, 10])

>>> v[2:]
array([ 3,

4,

5,

6,

7,

8,

9, 10])

>>> v[2:-1]
array([3, 4, 5, 6, 7, 8, 9])

Pascal.Neveu@supagro.inra.fr 40/73

Manipulations (cont.)

>>> v[2:-3]
array([3, 4, 5, 6, 7])
>>> v[::2]
array([1, 3, 5, 7, 9])
>>> v[1::2]
array([ 2, 4,

6,

8, 10])

>>> v[[3,1]]
array([4, 2])

Pascal.Neveu@supagro.inra.fr 41/73

Manipulations (cont.)
Array manipulations with logical
>>> v
array([ 1,

2,

3,

4,

5,

6,

7,

8,

9, 10])

>>> v>2
array([False, False, True, True, True, True, True,
True, True, True], dtype=bool)
>>> v[v>2]
array([ 3,

4,

5,

6,

7,

8,

9, 10])

>>> v[(v>2)*(v<5)]
array([3, 4])
>>> v[((v>2)&(v<5))]
array([3, 4])

Pascal.Neveu@supagro.inra.fr 42/73

Matrix manipulation with index


>>> A
array([[ 1,
[ 4,

2,
5,

3],
6]])

>>> A[1,2]
6
>>> A[(0,1),1]
array([2, 5])
>>> A[1,(1,2)]
array([5, 6])
>>> A[:,1]
array([2, 5])
>>> A[[1,0],[1,2]]
array([5, 3])
Pascal.Neveu@supagro.inra.fr 43/73

Matrix manipulation with logical

>>> A<3
array([[ True, True, False],
[False, False, False]], dtype=bool)
>>> A[A<3]
array([1, 2])
>>> A[A<3]=10
>>> A
array([[10, 10,
[ 4, 5,

3],
6]])

Pascal.Neveu@supagro.inra.fr 44/73

Structure manipulation
>>> a=arange(8)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> a.reshape(2,-1)
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
>>> a.reshape(-1,2)
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
Pascal.Neveu@supagro.inra.fr 45/73

Structure manipulation (cont.)

>>> a
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> a.reshape(-1,2).transpose()
>>> a.reshape(-1,2).T
array([[0, 2, 4, 6],
[1, 3, 5, 7]])

Pascal.Neveu@supagro.inra.fr 46/73

Matrix operations

>>> A=mat("1; 2; 3; 4; 5; 6")


>>> A
matrix([[1],
[2],
[3],
[4],
[5],
[6]])
>>> A.T
matrix([[1, 2, 3, 4, 5, 6]])

Pascal.Neveu@supagro.inra.fr 47/73

Matrix operations (cont.)


>>> A=mat("1 2 3 ; 4 5 6")
>>> B=A.T
matrix([[1, 4],
[2, 5],
[3, 6]])
>>> A*B
matrix([[14, 32],
[32, 77]])
>>> dot(A,B)
matrix([[14, 32],
[32, 77]])
Pascal.Neveu@supagro.inra.fr 48/73

Matrix operations (cont.)


>>> A=mat("1 2 3 ; 4 5 6")
>>> A=asarray(A)
>>> dot(A,B)
array([[14, 32],
[32, 77]])
>>> A*B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast

Pascal.Neveu@supagro.inra.fr 49/73

Matrix operations (cont.)


linear equation system: A X = b
In [10]: A
Out[10]:
matrix([[1, 2],
[2, 3]])
In [11]: b
Out[11]: array([0, 1])
In [12]: solve(A,b)
Out[12]: array([ 2., -1.])

Pascal.Neveu@supagro.inra.fr 50/73

Matrix operation: dimension computing


>>> x=array([pi*2 , pi*3])
>>> x
array([ 6.28318531, 9.42477796])
>>> x.round(3)
array([ 6.283, 9.425])
>>> A
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
>>> A.sum(axis=0)
array([ 5., 7., 9.])
>>> A.sum(axis=1)
array([ 6., 15.])

Pascal.Neveu@supagro.inra.fr 51/73

Matrix operation: dimension computing (cont.)


>>> A
array([[
[
[
[

0.52,
0.99,
0.5 ,
0.13,

>>> A[A>0.7]
array([ 0.99,

0.59,
0.88,
0.58,
0.03,

0.88,

0.3 ,
0.26,
0.29,
0.19,

0.44,
0.77,
0.41,
0.63,

0.05],
0.41],
0.26],
0.38]])

0.77])

>>> where(A>.6)
(array([1, 1, 1, 3]), array([0, 1, 3, 3]))

Pascal.Neveu@supagro.inra.fr 52/73

Matrix operation: dimension computing (cont.)


>>> A
array([[
[
[
[

0.52,
0.99,
0.5 ,
0.13,

0.59,
0.88,
0.58,
0.03,

0.3 ,
0.26,
0.29,
0.19,

0.44,
0.77,
0.41,
0.63,

0.05],
0.41],
0.26],
0.38]])

>>> sort(A.flatten())
array([ 0.03, 0.05, 0.13, 0.19, 0.26, 0.26, 0.29,...
0.3 , 0.38, 0.41, 0.41, 0.44, 0.5 , 0.52, 0.58,...
0.59, 0.63, 0.77, 0.88, 0.99])
>>> sort(A)
array([[ 0.05,
[ 0.26,
[ 0.26,
[ 0.03,

0.3 ,
0.41,
0.29,
0.13,

0.44,
0.77,
0.41,
0.19,

0.52,
0.88,
0.5 ,
0.38,

0.59],
0.99],
0.58],
0.63]])
Pascal.Neveu@supagro.inra.fr 53/73

Matrix operation: dimension computing (cont.)

>>> sort(A,axis=0)
array([[ 0.13, 0.03,
[ 0.5 , 0.58,
[ 0.52, 0.59,
[ 0.99, 0.88,

0.19,
0.26,
0.29,
0.3 ,

0.41,
0.44,
0.63,
0.77,

0.05],
0.26],
0.38],
0.41]])

Pascal.Neveu@supagro.inra.fr 54/73

Least squares for parameter optimization and graphics


>>> x
array([ 0, 1, 2, 3,... , 26, 27, 28, 29])
>>> y
array([ 1.696963, 7.498109, ... , 545.60116814, 577.57219145])
>>> figure(0)
>>> plot(x,y,ks)

Pascal.Neveu@supagro.inra.fr 55/73

Least squares for parameter optimization and graphics


(cont.)
>>> def f(p,x):
... return p[2]*x**2+p[1]*x+p[0]
...
>>> def err(p,x,y):
...
return f(p,x)-y
...
>>> p
array([0, 1, 2])
>>> pp = leastsq(err,p,args=(x,y))
>>> pp
(array([-1.39042612, 6.99088574, 0.45505577]), 1)
>>> ys=f(pp,x)
Pascal.Neveu@supagro.inra.fr 56/73

Least squares for parameter optimization and graphics


(cont.)
>>> figure(1) # open a window
>>> plot(x,y,ks, x, ys, r-, lw=2)
>>> ginput(1) # locating points on a graphic

See examples and gallery (code sources are available)


Pascal.Neveu@supagro.inra.fr 57/73
http://matplotlib.sourceforge.net/

A program
import sys
from numpy import *
from scipy import *
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# modele de "peche"
# x(t)=rx(t)*(1-x(t)/K)-qEx(t)
# 2 arguments r and E
# r : reproduction
# E : effort
# syntax checking
if ( size(sys.argv) != 3 ):
print Syntax error \n usage : +sys.argv[0]+ r E
exit(0)
r=float( sys.argv[1] ) # r
E=float( sys.argv[2] ) # E
Pascal.Neveu@supagro.inra.fr 58/73

A program (cont.)
# cond initials
x0=([8.0])
# temps
t=arange(0.0,80,0.003)
# capturability
q=0.25
# max
K=20.0
# axis labels
xl = plt.xlabel(temps)
yl = plt.ylabel(Biomass)
# graphic title visualize parameter value
titre=parameters : r=+sys.argv[1]+
... et E=+sys.argv[2]
Pascal.Neveu@supagro.inra.fr 59/73

A program (cont.)
ttl = plt.title(titre)
# diff eq of the modele
def funci(x,t):
return r*x*(1-x/K)-q*E*x
# integration init cond
y=odeint(funci,x0,t)

x0 and time

# visualisation
plt.plot(t,y)
plt.show()

Pascal.Neveu@supagro.inra.fr 60/73

Exercices
- Install python 2.7
- Install numpy, scipy, matplotlib and ipython modules
- Create v1 as numerical vector with values from 1 to 12
- Calculate the sum of v1 elements
- Calculate the number of v1 elements that are strictly greater than 5
- Calculate the sum of v1 elements that are strictly greater than 5
- Create a vector V of length 100 that contains random values in [0,1]
Use rand from numpy.random library.
- Give a simple instruction to get 12! value (factorial)
- Create the matrix A
array([[ 0,
[ 4,
[ 8,

1, 2, 3],
5, 6, 7],
9, 10, 11]])

- calculate A*A (matrix product)


- Create a matrix A of 20 rows and 6 columns with
random uniform elements
- round A to 3 decimals

Pascal.Neveu@supagro.inra.fr 61/73

Exercices (cont.)
- Calculate row means of A
Sergio has 3 daughters, we know:
The sum of 3 daughter ages is 66 years.
The double of the age of one of them is equal to the sum
of the 2 others.
The older has 12 years less than the sum of ages of
the 2 youngest daughters.
Give ages of the 3 daughters.
- x and y row vectors. We need to remove
values of vector x that are already in vector y.
For example, if x=[2, 1, 4, 5, 7, 6] and if
y = [1, 4, 7]. We want x= [2, 5, 6]
x=random(20)*3 and y=x**2+random(20)
make the plot of y vs x.
locate on the graphics the curve maximum

Pascal.Neveu@supagro.inra.fr 62/73

Practice and performance: any and all


>>> x=random(200)
>>> x
array([ 0.89977878,
....,
>>> all(x>.2)
False

0.13654671,
0.15800227,

0.33486046,
0.46035374,

...
0.90776494])

>>> all(x>.002)
True
>>> any(x>.9)
True
>>> any(x>.999)
False
Pascal.Neveu@supagro.inra.fr 63/73

Practice and performance


Try to not use loop
>>> import time
>>> a=random(2000000)

>>> t1=time.clock()
>>> n=0
>>> for i in range(2000000):
...
if a[i]>.5 : n=n+1
...
>>> n
1001192
>>> t2=time.clock()
>>> t2-t1
1.47

>>> t1=time.clock()
>>> n=sum(a>.5)
>>> n
1001192
>>> t2=time.clock()
>>> t2-t1
0.030000000000000027

Pascal.Neveu@supagro.inra.fr 64/73

Practice and performance (cont.)


>>> size(a)
2000000

>>> t1=time.clock()
>>> for i in range(2000000):
...
if a[i]>.5 : a[i]=1
...
>>> t2=time.clock()
>>> t2-t1
1.5600000000000001

>>> a[(a>.5)]=1
>>>
>>> t3=time.clock()
>>> t3-t2
0.020000000000000018

Pascal.Neveu@supagro.inra.fr 65/73

Practice and performance (cont.)


>>> size(a)
2000000

>>> t1=time.clock()
>>> for i in range(2000000):
...
if a[i]>.5 : a[i]=log(a[i])
...
>>> t2=time.clock()
>>> t2-t1
3.9399999999999995

>>> a[(a>.5)]=log(a[(a>.5)])
>>>
>>> t3=time.clock()
>>> t3-t2
0.010000000000000675

Pascal.Neveu@supagro.inra.fr 66/73

Practice and performance (cont.)

all vs sum
>>> t1=time.clock()
>>> n=sum(a>0)
>>>
>>> t2=time.clock()
>>> t2-t1
0.020000000000000018

>>> all(a>0)
True
>>> t3=time.clock()
>>> t3-t2
0.0099999999999997868

Pascal.Neveu@supagro.inra.fr 67/73

Practice and performance


>>> t1=time.clock()
>>> n=0
>>> for i in range(1000):
...
for j in range(1000):
...
if ((A[i,j]> .01) and (A[i,j]<0.3)): n=n+1
...
...
>>> t1-time.clock()
1.54
___________________________________________________
>>> t1=time.clock()
>>> n=0
>>> for i in range(1000):
...
for j in range(1000):
...
if ((A[i,j]< .03) and (A[i,j]>0.01)): n=n+1
...
...
>>> t1-time.clock()
Pascal.Neveu@supagro.inra.fr 68/73
0.81000000000000005

Practice and performance


>>> x=arange(1000000)
>>> y=zeros(1000000-2)
>>>
>>>
...
...
>>>
>>>
1.0

t1=time.clock()
for i in range(1000000-2):
y[i]=x[i]+x[i+1]+x[i+2]
t2=time.clock()
t2-t1

>>> t1=time.clock()
>>> y=x[:-2]+x[1:-1]+x[2:]
>>> t2=time.clock()
>>> t2-t1
0.020000000000000018
Pascal.Neveu@supagro.inra.fr 69/73

Practice and performance (cont.)


Some numerical aspects
>>> 2.4703e-324>0
False
>>> 2.4704e-324>0
True
>>> (1+10e-16)>1
True
>>> (1+10e-17)>1
False

Pascal.Neveu@supagro.inra.fr 70/73

Practice and performance (cont.)


>>> a
1e-08
>>> b
1e-08
>>> c
10000
>>> (((a*b) *c) - (a* (b*c)))==0
False
>>> (((a*b) *c) - (a* (b*c)))
2.0194839173657902e-28

Pascal.Neveu@supagro.inra.fr 71/73

Practice and performance (cont.)


>>> from mpmath import *
>>> mp.dps=20
>>> x=mpf(2.01234567890123456789012345678)
>>> y=sqrt(x)
>>> z=exp(y)
>>> w=ln(z)**2
>>> w
mpf(2.0123456789012345678888)
>>> mp.dps=35
>>> x=mpf(2.01234567890123456789012345678)
>>> y=sqrt(x)
>>> z=exp(y)
>>> w=ln(z)**2
>>> w
mpf(2.012345678901234567890123456780000004)
Pascal.Neveu@supagro.inra.fr 72/73

You might also like