Professional Documents
Culture Documents
Le langage Python seul ne sait pas faire grand chose dans le domaine mathmatique, comme
tracer une fonction, calculer des valeurs de fonctions usuelles, raliser des oprations matricielles,...
Cependant, de nombreux modules ont t dvelopps pour pallier ce manque, parmi lesquels in
convient de citer :
scipy
numpy
matplotlib
A noter que le module pylab intgre ces trois modules et ipython.
Lobjectif de ce document nest bien entendu pas dtre exhaustif sur ce quil est possible de
faire avec python et ces modules, mais juste de donner quelques points dentre sur ces librairies
et de proposer des illustrations par lexemple de leur utilisation. Dans la mesure du possible, les
exemples collent "pas trop loin" du programme officiel de maths MPSI.
1.1
Types
Les types de base qui peuvent tre utiles dans la suite sont les suivants :
1.1.1
Types numriques
Conteneurs
1.2
Oprateurs lmentaires
1.3
Pour disposer des fonctions mathmatiques usuelles, la librairie dorigine du python se nomme
math. On peut alors dimporter juste les fonctions ncessaires par from math import cos, log ou
toutes les fonctions mathmatiques par from math import *. Dans le premier cas linconvnient
est quil faut savoir lavance les fonctions utilises par la suite, dans le deuxime cas on risque de
surcharger inutilement la mmoire.
A noter que pour manipuler des complexes, il faut importer le module cmath en plus du module
math (par exemple pour raliser des produits de complexes).
1.4
Pour illustrer les capacits de base de Python, nous proposons de calculer de manire numrique
Rb
la valeur de I = a f (x)dx, en utilisant trois mthodes classiques :
n1
X
xi + xi+1
la mthode des rectangles :I
(xi+1 xi )f
2
i=0
#
"
n1
X
f (a)+f (b)
la mthode des trapzes : I h
+
f (xi )
2
i=1
"
#
n1
n1
X
X
la mthode de Simpson : I h6 f (a) + f (b) + 4
f (x2i+1 ) + 2
f (x2i ) avec h = ba
n
i=0
i=1
et xk = a + k h2
et o (x0 xn ) est une subdivision rgulire de lintervalle [a, b] de pas h
Le code 1 donne le source python permettant de raliser ces trois approximations.
# c o d i n g : u t f 8
def r e c t a n g l e s ( f , a , b , n ) :
#Methode d e s r e c t a n g l e s
S=0
f o r i in x r a n g e ( 0 , n ) :
x i=a+(ba ) i / f l o a t ( n )
x j=a+(ba ) ( i +1)/ f l o a t ( n )
S+= f ( ( x i+x j ) / 2 . 0 ) ( xj x i )
return S
def t r a p e z e s ( f , a , b , n ) :
#Methode d e s t r a p e z e s
S=0
f o r i in x r a n g e ( 0 , n ) :
x i=a+(ba ) i / f l o a t ( n )
x j=a+(ba ) ( i +1)/ f l o a t ( n )
S+= ( f ( x i )+f ( x j ) ) / 2 . 0 ( xj x i )
return S
def simpson ( f , a , b , n ) :
#Methode de Simpson
S=0
f o r i in x r a n g e ( 0 , n ) :
x i=a+(ba ) i / f l o a t ( n )
x j=a+(ba ) ( i +1)/ f l o a t ( n )
S+= ( xj x i ) ( f ( x i ) +4 f ( ( x i+x j ) / 2 . 0 )+f ( x j ) ) / 6 . 0
return S
def f n ( x ) :
#f o n c t i o n a i n t e g r e r
return 4 . 0 / ( 1 + ( x3) ( x3) )
def main ( ) :
print " par rectangles : " , r e c t a n g l e s ( fn , 0 . , 5 . , 1 0 0 ) ;
print " par trapzes : " , t r a p e z e s ( fn , 0 . , 5 . , 1 0 0 ) ;
print " par Simpson : " , simpson ( fn , 0 . , 5 . , 1 0 0 ) ;
main ( )
Listing 1 Approximation numrique dune intgrale par trois mthodes classiques
1.5
Prenons un exemple classique, celui du calcul dune estimation du nombre dor laide de la
suite de Fibonacci. Le code 2 prsente le calcul des n premiers termes de la suite de Fibonacci
u0 = 1, u1 = 1 et un = un1 + un2 , n 2 ainsi que la valeur absolue de la diffrence avec le
nombre dor 1+2 5 .
# c o d i n g : u t f 8
def f i b o n a c c i ( n ) :
a = b = 1.
f o r i in r a n g e ( n ) :
a, b = a + b, a
print abs ( ( a /b ) (1+50.5) / 2 )
return b
def main ( ) :
fibonacci (30)
main ( )
Listing 2 Calcul approch du nombre dor
Exercice 1 Proposer un code permettant de calculer ces mmes quantits de manire rcursive.
Exercice 2 Proposer un code permettant de calculer la somme des lments dune suite quelconque
indics par un ensemble dentiers J
1.6
Le code 3 prsente un calcul simple dun zro dune fonction dans un intervalle donn, en
utilisant
une approche dichotomique.
# c o d i n g : u t f 8
def f ( x ) :
return x 2
+20x 12
def z e r o ( f , a , b ) :
i f f ( a ) f ( b ) >0:
print ( La fonction ne s annule pas dans l intervalle [ +s t r ( a )+ , +s t r ( b )
+] )
return 0
while ( abs ( ab )>1e 3) :
m=(a+b ) / 2 .
print m
i f f (m) f ( a ) >0:
a=m
else :
b=m
print ( la solution de f ( x ) =0 est +s t r (m) )
return m
print ( z e r o ( f , 1 0 . , 1 0 . ) )
Exercice 3 Produire un code qui calcule le zro dune fonction en utilisant la mthode de Newton
(algorithme 1) :
Algorithm 1: Mthode de Newton
Entres: N, , f, fp , x0
n 0
xn x0
rpter
n)
xn xn ffp(x
(xn )
nn+1
si fp (xn ) < alors
Division par zero
fin
n)
jusqu
ffp(x
(xn )
< OU n > N ;
Exercice 4 Calculer une approximation de en utilisant par exemple les deux rsultats classiques :
X
1
2
=
6
n2
n=1
X
4n2
=
2
4n2 1
n=1
et
2.1
Ces modules fournissent un ensemble dobjets ainsi quun groupes de fonctions permettant de
manipuler nombre dobjets de faon simple et trs performantes dans le cadre du calcul scientifique.
Voici la description donne par le site officiel de Numpy (http ://www.scipy.org, numpy.scipy.org )
SciPy is a collection of mathematical algorithms and convenience functions built on the Numpy
extension for Python. It adds significant power to the interactive Python session by exposing the
user to high-level commands and classes for the manipulation and visualization of data. With SciPy,
an interactive Python session becomes a data-processing and system-prototyping environment rivaling sytems such as MATLAB, IDL, Octave, R-Lab, and SciLab. NumPy is the fundamental
package needed for scientific computing with Python. It contains among other things :
a powerful N-dimensional array object - sophisticated (broadcasting) functions tools for integrating C/C++ and Fortran code
useful linear algebra, Fourier transform, and random number capabilities.
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data types can be defined. This allows NumPy to seamlessly and
speedily integrate with a wide variety of databases.
Scipy est un ensemble qui comprend de nombreux modules utiles pour des scientifiques :
cluster : information theory functions (currently, vq and kmeans)
weave : compilation of numeric expressions to C++ for fast execution
fftpack : fast Fourier transform module based on fftpack and fftw when available
ga : genetic algorithms
io : reading and writing numeric arrays, MATLAB .mat, and Matrix Market .mtx files
integrate : numeric integration for bounded and unbounded ranges. ODE solvers.
interpolate : interpolation of values from a sample data set.
optimize : constrained and unconstrained optimization methods and root-finding algorithms
signal : signal processing (1-D and 2-D filtering, filter design, LTI systems, etc.)
special : special function types (bessel, gamma, airy, etc.)
stats : statistical functions (stdev, var, mean, etc.)
linalg : linear algebra and BLAS routines based on the ATLAS implementation of LAPACK
sparse : Some sparse matrix support. LU factorization and solving Sparse linear systems.
Enfin Matplotlib permet de visualiser en 2D des donnes.
2.2
Numpy ajoute le type array qui est similaire une liste (list) avec la condition supplmentaire
que tous les lments sont du mme type.
Le code 4 prsente quelques exemples dinstantiation de matrices simples.
# c o d i n g : u t f 8
import numpy a s np
# t a b l e a u 1D
a1 = np . a r r a y ( [ 1 , 2 , 3 , 4 ] , f l o a t )
print a1
#t a b l e a u 2D
a2=np . a r r a y ( [ [ [ 1 , 2 ] , [ 3 , 4 ] ] , [ [ 5 , 6 ] , [ 7 , 8 ] ] ] )
print a2
#m a t r i c e s de 1
un=np . o n e s ( 5 )
print un
#m a t r i c e d i a g o n a l e
d = np . d i a g ( a1 )
print d
#m a t r i c e bande
d1 = np . d i a g ( a1 , 1)
print d1
#m a t r i c e c o e f f i c i e n t s a l a t o i r e s dans [ 0 , 1 ]
r = np . random . rand ( 3 , 3 )
print r
# Identit
i = np . e y e ( 5 )
print i
# Matrice n u l l e
z = np . z e r o s ( 5 )
print z
Listing 4 Dfinitions de matrices
Les oprations classiques sur la matrices sont disponibles laide de numpy : addition, multiplication par un scalaire, produit matriciel...Le code 5 prsente quelques exemples de ces oprations.
# c o d i n g : u t f 8
import numpy a s np
A = np . random . rand ( 3 , 3 )
B=np . d i a g ( [ 1 . , 2 . , 3 . ] )
v = np . a r r a y ( [ 3 . , 4 . , 5 . ] ,
float )
# addition
C1 = A+B
C2 = 2.+A
#m u l t i p l i c a t i o n
D1 = 2A
#c o e f f i c i e n t s de A m u l t i p l i s par 2
D2 = B3
#c o e f f i c i e n t s de B l a p u i s s a n c e 3
D3 = AB
# m u l t i p l i c a t i o n terme terme
D4 = np . dot (A, B)# m u l t i p l i c a t i o n m a t r i c i e l l e
D5 = np . dot (A, v )#p r o d u i t m a t r i c e / v e c t e u r
D6 = np . kron (A, B)#p r o d u i t de Kronecker
#t e s t
E1 = A<B#r e n v o i e une m a t r i c e de b o o l e n s e f f e c t u a n t l e t e s t
bo = np . a r r a y ( [ 1 , 0 . , 0 ] , b o o l )
E2=B [ bo ]#e x t r a i t l e s l m e n t s de B q u i c o r r e s p o n d e n t l a v a l e u r v r a i e de bo
E3=A[ A> 0 . 5 ]
# c o d i n g : u t f 8
import numpy a s np
import numpy . l i n a l g a s n l
A = np . random . rand ( 3 , 3 )
b = np . a r r a y ( [ 3 . , 4 . , 5 . ] ,
float )
#T r a n s p o s i t i o n d une m a t r i c e
Aprime=A. t r a n s p o s e ( )
#Rang d une m a t r i c e
r = np . rank (A)
#I n v e r s e d une m a t r i c e
Ainv = n l . i n v (A) #a t t e n t i o n t e s t e r s i A e s t i n v e r s i b l e . . .
#R s o l u t i o n de s y s t m e s l i n a i r e s
x = n l . s o l v e (A, b )
#c a l c u l d e s l m e n t s p r o p r e s
n l . e i g (A) #v a l e u r s p r o p r e s , m a t r i c e de p a s s a g e
#C a l c u l de normes
n1 = n l . norm (A, np . i n f ) ;
n2 = n l . norm (A,np . i n f ) ;
n3 = n1 = n l . norm (A, 2 ) ;
n4 = n1 = n l . norm (A, fro ) ;
akk
k1
X
!2
a2kp
p=1
pour i {k + 1 n} faire
!
k1
X
1
aik akk aik
aip akp
p=1
fin
fin
Notons que numPy propose de nombreux autres atouts, que nous vous conseillons de dcouvrir dans la documentation de ce module. A titre dexemple, citons la classe poly1d qui gre les
polynmes une variable, documente comme suit :
c l a s s numpy . p o l y 1 d ( c_or_r , r =0 , v a r i a b l e=None ) [ s o u r c e ]
A oned i m e n s i o n a l p o l y n o m i a l c l a s s .
A c o n v e n i e n c e c l a s s , used t o e n c a p s u l a t e n a t u r a l o p e r a t i o n s on p o l y n o m i a l s s o t h a t
s a i d o p e r a t i o n s may t a k e on t h e i r customary form in code ( s e e Examples ) .
P a r a m e t e rs :
c_or_r : a r r a y _ l i k e
The p o l y n o m i a l s c o e f f i c i e n t s , in d e c r e a s i n g powers , or i f t h e v a l u e o f t h e s e c o n d
p a r a m e t e r i s True , t h e p o l y n o m i a l s r o o t s ( v a l u e s where t h e p o l y n o m i a l e v a l u a t e s
t o 0 ) . For example , p o l y 1 d ( [ 1 , 2 , 3 ] ) r e t u r n s an o b j e c t t h a t r e p r e s e n t s ,
wh er ea s p o l y 1 d ( [ 1 , 2 , 3 ] , True ) r e t u r n s one t h a t r e p r e s e n t s .
r : bool , o p t i o n a l
I f True , c_or_r s p e c i f i e s t h e p o l y n o m i a l s r o o t s ; t h e d e f a u l t i s F a l s e .
variable : str , optional
Changes t h e v a r i a b l e used when p r i n t i n g p from x t o v a r i a b l e ( s e e Examples ) .
Examples
Construct the polynomial :
>>> p = np . p o l y 1 d ( [ 1 , 2 , 3 ] )
>>> print np . p o l y 1 d ( p )
2
1 x + 2 x + 3
Evaluate the polynomial at :
>>> p ( 0 . 5 )
4.25
Find t h e r o o t s :
>>> p . r
a r r a y ( [ 1 . + 1 . 4 1 4 2 1 3 5 6 j , 1. 1.41421356 j ] )
>>> p ( p . r )
a r r a y ( [ 4.44089210 e 16+0. j ,
4.44089210 e 16+0. j ] )
These numbers in t h e p r e v i o u s l i n e r e p r e s e n t ( 0 , 0 ) t o machine p r e c i s i o n
Show t h e c o e f f i c i e n t s :
>>> p . c
array ( [ 1 , 2 , 3 ] )
D i s p l a y t h e o r d e r ( t h e l e a d i n g z e r o c o e f f i c i e n t s a r e removed ) :
>>> p . o r d e r
2
Show t h e c o e f f i c i e n t o f t h e kth power in t h e p o l y n o m i a l ( which i s e q u i v a l e n t t o p .
c [ ( i +1) ] ) :
>>> p [ 1 ]
2
P o l y n o m i a l s can be added , s u b t r a c t e d , m u l t i p l i e d , and d i v i d e d ( r e t u r n s q u o t i e n t and
remainder ) :
>>> p p
poly1d ( [ 1 , 4 , 10 , 12 ,
9])
>>> ( p 3 + 4 ) / p
( poly1d ( [
1. ,
4. ,
10. ,
12. ,
9 . ] ) , poly1d ( [ 4 . ] ) )
a s a r r a y ( p ) g i v e s t h e c o e f f i c i e n t a r r a y , s o p o l y n o m i a l s can be used in a l l f u n c t i o n s
that accept arrays :
10
>>> p 2 # s q u a r e o f p o l y n o m i a l
poly1d ( [ 1 , 4 , 10 , 12 ,
9])
>>> np . s q u a r e ( p ) # s q u a r e o f i n d i v i d u a l c o e f f i c i e n t s
array ( [ 1 , 4 , 9 ] )
The v a r i a b l e used in t h e s t r i n g r e p r e s e n t a t i o n o f p can be m o d i f i e d , u s i n g t h e
v a r i a b l e parameter :
>>> p = np . p o l y 1 d ( [ 1 , 2 , 3 ] , v a r i a b l e=z )
>>> print p
2
1 z + 2 z + 3
C o n s t r u c t a p o l y n o m i a l from i t s r o o t s :
>>> np . p o l y 1 d ( [ 1 , 2 ] , True )
p o l y 1 d ( [ 1 , 3, 2 ] )
This i s t h e same p o l y n o m i a l a s o b t a i n e d by :
>>> np . p o l y 1 d ( [ 1 , 1]) np . p o l y 1 d ( [ 1 , 2])
p o l y 1 d ( [ 1 , 3, 2 ] )
Attributes
coeffs
order
variable
Methods
__call__ ( v a l )
d e r i v ( [m] )
i n t e g ( [ m, k ] )
Return a d e r i v a t i v e o f t h i s p o l y n o m i a l .
Return an a n t i d e r i v a t i v e ( i n d e f i n i t e i n t e g r a l ) o f t h i s p o l y n o m i a l .
2.3
Scipy est construit partir de Numpy, ce qui signifie quil faut avoir le module Numpy pour
faire fonctionner le module Scipy. En effet nombre de fonctions ainsi que le type ndarray de Scipy
sont en fait ceux dfinis dans Numpy.
2.3.1
Intgration numrique
Scipy propose une srie de classes pour lintgration. Cet ensemble se trouve regroup dans le
sous-module scipy.integrate. Lintgration peut se faire sur un intervalle, partir dun chantillon
de points ou encore servir rsoudre des quations diffrentielles (cf. paragraphe 2.3.2)
Le code 9 reprend le calcul de lintgrale dcrit dans le paragraphe 1.4, mais en utilisant trois
fonctions fournies par la librairie
11
# c o d i n g : u t f 8
from numpy import
from s c i p y import i n t e g r a t e
def f n ( x ) :
#f o n c t i o n a i n t e g r e r
return 4 . 0 / ( 1 + ( x3) ( x3) )
def main ( ) :
print " par Scipy : " , i n t e g r a t e . quad ( fn , 0 , 5 )
print " Romberg par Scipy : " , i n t e g r a t e . romberg ( fn , 0 , 5 )
#S u b d i v i s i o n de l i n t e r v a l l e par pas r g u l i e r
x = linspace (0 ,5 ,1000)
y=f n ( x )
print " trapezes par Spicy " , i n t e g r a t e . t r a p z ( y , x , dx = 0 . 1 )
main ( )
Listing 9 Approximation numrique dune intgrale en utilisant Spicy
2.3.2
Listing 10 Rsolution par intgration dune quation diffrentielle ordinaire en utilisant Spicy
12
2.3.3
Interpolation
Scipy possde un module dinterpolation assez complet, qui comprend plusieurs mthodes dinterpolation dfinies sous formes de classes. Il est possible dutiliser des interpolations linaire ou
cubique par exemple. Le code 11 montre quelques appels de ces mthodes. Notons quil est ncessaire
dinstancier la classe pour lutiliser. La figure 1 prsente le rsultat graphique obtenu.
# c o d i n g : u t f 8
import s c i p y a s sp
import numpy a s np
from s c i p y . i n t e r p o l a t e import i n t e r p 1 d
from m a t p l o t l i b . p y p l o t import
x_measure = np . l i n s p a c e ( 0 . , 1 , 1 0 )
b r u i t = np . random . u n i f o r m ( 0 . 1 , 0 . 1 , 1 0 )
y_measure = np . s i n ( 2 np . p i x_measure ) +np . tan ( 2 np . p i x_measure ) + b r u i t
# i n s t a n c i a t i o n s de l a c l a s s e i n t e r p o l a t i o n
i n t e r p _ l i n = i n t e r p 1 d ( x_measure , y_measure )
i n t e r p _ c u b i c = i n t e r p 1 d ( x_measure , y_measure , k i n d= cubic )
interp_quad = i n t e r p 1 d ( x_measure , y_measure , k i n d= quadratic ) #
x_computed = np . l i n s p a c e ( 0 , 1 . , 1 0 0 )
y _ i n t _ l i n = i n t e r p _ l i n ( x_computed )
y_int_cub = i n t e r p _ c u b i c ( x_computed )
y_int_quad = interp_quad ( x_computed )
import m a t p l o t l i b . p y p l o t a s p l t
p l t . p l o t ( x_measure , y_measure , o , x_computed , y_int_lin , - , x_computed , y_int_cub ,
-- , x_computed , y_int_quad , * )
p l t . l e g e n d ( [ data , linear , cubic , quad ] , l o c= best )
p l t . show ( )
2.4
Le module Matplotlib, comme son nom lindique, soccupe du trac graphique. Nous avons
dj vu un exemple dutilisation de ce module dans la partie interpolation. Le code 12 et la
figure 2 donnent de nouveaux exemples, en illustrant certaines possibilits (titres, labels, types de
courbes, couleurs...), tandis que le code 13 et la figure 3 dmontrent quil est possible dafficher
simultanment plusieurs graphes sur une mme figure.
13
t 1=np . l i n s p a c e ( 1 , 5 , 1 0 )
t 2=np . l i n s p a c e ( 1 , 5 , 2 0 )
p l t . p l o t ( t1 , t1 , r - - , t1 , t 1 2 , bs , t2 , np . l o g ( t 2 ) 3 , g ^ - )
p l t . x l a b e l ( " Abcisses " )
p l t . y l a b e l ( fonctions )
p l t . l e g e n d ( [ courbe 1 , courbe 2 , courbe 3 ] , l o c= best )
p l t . t i t l e ( " Zoulies courbes " )
p l t . show ( )
14
.
.
.
.
.
subplot (221)
x l a b e l ( " Abcisses " )
p l o t ( t1 , f ( t 1 ) , bo , t2 , f ( t 2 ) , k )
x l a b e l ( " Abcisses " )
y l a b e l ( "f" )
plt
plt
plt
plt
.
.
.
.
subplot (222)
p l o t ( t2 , g ( t 2 ) , r - - )
x l a b e l ( " Abcisses " )
y l a b e l ( "g" )
plt
plt
plt
plt
.
.
.
.
subplot (223)
p l o t ( t1 , h ( t 1 ) , b - )
x l a b e l ( " Abcisses " )
y l a b e l ( "h" )
15
p l t . show ( )
Listing 13 Affichage de plusieurs figures
16
from math import
import numpy a s np
import m a t p l o t l i b . p y p l o t a s p l t
# V a l e u r s du p a r a m t r e s pour l e s p o i n t s t r a c s l e l o n g de l a c o u r b e
l t = np . l i n s p a c e ( 0 , 2 pi , 1 0 0 )
Listing 14 Quelques courbes paramtres
17
18