Maths et Python - Apprendre en ligne
Transcription
Maths et Python - Apprendre en ligne
Mathématiques et Python Le langage Python seul ne sait pas faire grand chose dans le domaine mathématique, comme tracer une fonction, calculer des valeurs de fonctions usuelles, réaliser des opérations matricielles,... Cependant, de nombreux modules ont été développés pour pallier ce manque, parmi lesquels in convient de citer : – scipy – numpy – matplotlib A noter que le module pylab intègre ces trois modules et ipython. L’objectif de ce document n’est bien entendu pas d’être exhaustif sur ce qu’il est possible de faire avec python et ces modules, mais juste de donner quelques points d’entrée sur ces librairies et de proposer des illustrations par l’exemple de leur utilisation. Dans la mesure du possible, les exemples collent "pas trop loin" du programme officiel de maths MPSI. 1 Ce que l’on peut faire sans les modules... 1.1 Types Les types de base qui peuvent être utiles dans la suite sont les suivants : 1.1.1 Types numériques – integer (attention à la division entre entiers !) – float – complex : l’imaginaire pur i est noté j en python. A tout instant, il est possible d’accéder au type d’une variable a en tapant type(a) Toute variable définie avec un type change de type lors d’une nouvelle affectation. On peut aussi changer de type à l’aide des fonctions int(), f loat(). L’une des caractéristiques importantes de Python est le typage dynamique. Cependant, si certaines opérations provoquent un changement de type, certaines restent interdites. 1.1.2 Conteneurs – listes (par exemple tab = [1, 2, 3, 4, 5]) – index (les indices de listes commencent à 0 : par exemple a[2] donne 3) – slices (a[1 : 3] donne [2, 3]) Le typage dans les listes est faible, on peut combiner différents types numériques (ou non comme des chaînes de caractères, des booléens...) De nombreuses fonctions sont associées à ces listes (concaténation, recherche de sous-chaînes...). 1 1.2 Opérateurs élémentaires Les opérateurs classiques suivantes sont disponibles : 1. +,-,*,/ 2. modulo : % 3. exposant : ** 4. division entière :// (par exemple 9//2=4) 5. opérateurs de comparaison : ==, !=, <>, <,<=,>,>= 6. opérateurs d’affectation : =,+=,-=,*=,/=,%=,**=,//= 7. les opérateurs bit à bit : & (et),k (ou), ˆ (XOR),˜ (complément à 1), <<(décalage à gauche), >> (décalage à droite) 8. opérateurs logiques : and, or, not 9. opérateurs d’appartenance (sur des types comme des chaînes) : in, not in 10. opérateurs d’identité : is, is not 1.3 La librairie standard math Pour disposer des fonctions mathématiques usuelles, la librairie d’origine du python se nomme math. On peut alors d’importer juste les fonctions nécessaires par from math import cos, log ou toutes les fonctions mathématiques par from math import *. Dans le premier cas l’inconvénient est qu’il faut savoir à l’avance les fonctions utilisées par la suite, dans le deuxième cas on risque de surcharger inutilement la mémoire. A noter que pour manipuler des complexes, il faut importer le module cmath en plus du module math (par exemple pour réaliser des produits de complexes). 1.4 Un exemple : calcul d’intégrales Pour illustrer les capacités de base de Python, nous proposons de calculer de manière numérique Rb la valeur de I = a f (x)dx, en utilisant trois méthodes classiques : n−1 X xi + xi+1 – la méthode des rectangles :I ≈ (xi+1 − xi )f 2 i=0 # " n−1 X f (a)+f (b) – la méthode des trapèzes : I ≈ h + f (xi ) 2 i=1 " # n−1 n−1 X X – la méthode de Simpson : I ≈ h6 f (a) + f (b) + 4 f (x2i+1 ) + 2 f (x2i ) avec h = b−a n i=0 i=1 et xk = a + k h2 et où (x0 · · · xn ) est une subdivision régulière de l’intervalle [a, b] de pas h Le code 1 donne le source python permettant de réaliser ces trois approximations. 2 # −∗− 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+(b−a ) ∗ i / f l o a t ( n ) x j=a+(b−a ) ∗ ( 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+(b−a ) ∗ i / f l o a t ( n ) x j=a+(b−a ) ∗ ( 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+(b−a ) ∗ i / f l o a t ( n ) x j=a+(b−a ) ∗ ( 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 + ( x−3) ∗ ( x−3) ) def main ( ) : print " par rectangles : " , r e c t a n g l e s ( fn , 0 . , 5 . , 1 0 0 ) ; print " par trapèzes : " , 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 numérique d’une intégrale par trois méthodes classiques 1.5 Un autre exemple autour des suites Prenons un exemple classique, celui du calcul d’une estimation du nombre d’or à l’aide de la suite de Fibonacci. Le code 2 présente le calcul des n premiers termes de la suite de Fibonacci u0 = 1, u1 = 1 √et un = un−1 + un−2 , n ≥ 2 ainsi que la valeur absolue de la différence avec le nombre d’or 1+2 5 . 3 # −∗− 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+5∗∗0.5) / 2 ) return b def main ( ) : fibonacci (30) main ( ) Listing 2 – Calcul approché du nombre d’or Exercice 1 Proposer un code permettant de calculer ces mêmes quantités de manière récursive. Exercice 2 Proposer un code permettant de calculer la somme des éléments d’une suite quelconque indicés par un ensemble d’entiers J 1.6 Un dernier exemple : zéro d’une fonction Le code 3 présente un calcul simple d’un zéro d’une 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 +20∗x −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 ( a−b )>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 . ) ) Listing 3 – Zéro d’une fonction sur un intervalle par dichotomie. 4 Exercice 3 Produire un code qui calcule le zéro d’une fonction en utilisant la méthode de Newton (algorithme 1) : Algorithm 1: Méthode de Newton Entrées: N, , f, fp , x0 n← 0 xn ← x0 répéter n) xn ← xn − ffp(x (xn ) n←n+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 résultats classiques : ∞ X 1 π2 = 6 n2 n=1 2 ∞ X 4n2 π = 2 4n2 − 1 n=1 et ... Et là où ça va mieux : utilisation des librairies Python présente l’avantage de recourir aux modules pour le développement de fonctions ou d’ensembles de fonctionnalités spécifiques. Cela permet une grande flexibilité et une dynamique de développement importante. Parmi ces modules nous nous intéressons particulièrement dans la suite à Numpy, Scipy et Matplotlib. Suivant la distribution de Python choisie, l’ensemble de ces modules, avec d’autres, est automatiquement installé lors de l’installation de Python. Si ce n’est pas le cas il y a toujours la possibilité de les installer a posteriori. 2.1 Présentation rapide des modules Ces modules fournissent un ensemble d’objets ainsi qu’un groupes de fonctions permettant de manipuler nombre d’objets de façon simple et très performantes dans le cadre du calcul scientifique. Voici la description donnée 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. 5 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 données. 2.2 Quelques exemples de Numpy Numpy ajoute le type array qui est similaire à une liste (list) avec la condition supplémentaire que tous les éléments sont du même type. Le code 4 présente quelques exemples d’instantiation de matrices simples. 6 # −∗− 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 – Définitions de matrices Les opérations classiques sur la matrices sont disponibles à l’aide de numpy : addition, multiplication par un scalaire, produit matriciel...Le code 5 présente quelques exemples de ces opérations. 7 # −∗− 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 = 2∗A #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 = B∗∗3 #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 = A∗B # 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 ] Listing 5 – Opérations sur les matrices Bien entendu, numpy permet facilement de faire du calcul numérique matriciel : calcul du rang d’une matrice, inversion d’une matrice, résolution de systèmes linéaires. A titre d’exemple, le code 6 présente quelques possibilités offertes par le module. 8 # −∗− 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 ’ ) ; Listing 6 – Un peu d’algèbre linéaire avec numpy Exercice 5 Proposer un code qui code la décomposition de Cholesky d’une matrice A. Comparer avec l’appel à numpy.linalg.cholesky. Pour rappel, l’algorithme de Cholesky est le suivant : Algorithm 2: Méthode de Cholesky pour k ∈ {1 · · · n} faire akk ← akk − k−1 X !2 a2kp p=1 pour i ∈ {k + 1 · · · n} faire ! k−1 X 1 aik ← akk aik − aip akp p=1 fin fin Notons que numPy propose de nombreux autres atouts, que nous vous conseillons de découvrir dans la documentation de ce module. A titre d’exemple, citons la classe poly1d qui gère les polynômes à une variable, documentée comme suit : 9 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 one−d 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 k−th 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 : Listing 7 – Documentation de la classe poly1d 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 . Listing 8 – Documentation de la classe poly1d : suite Exercice 6 Proposer un code, utilisant la classe poly1d, et codant les polynômes de Legendre : P0 (x) = 1, P1 (x) = x, et pour tout entier n > 0 (n + 1)Pn+1 (x) = (2n + 1)xPn (x) − nPn−1 (x). 2.3 Quelques exemples de Scipy Scipy est construit à partir de Numpy, ce qui signifie qu’il 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 définis dans Numpy. 2.3.1 Intégration numérique Scipy propose une série de classes pour l’intégration. Cet ensemble se trouve regroupé dans le sous-module scipy.integrate. L’intégration peut se faire sur un intervalle, à partir d’un échantillon de points ou encore servir à résoudre des équations différentielles (cf. paragraphe 2.3.2) Le code 9 reprend le calcul de l’intégrale décrit 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 + ( x−3) ∗ ( x−3) ) 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 numérique d’une intégrale en utilisant Spicy 2.3.2 Résolution d’une équation différentielle ordinaire 2 On souhaite par exemple résoudre l’équation différentielle ddt2y = ay + b dy dt pour t ∈ [0, 10] et une condition initiale sur y et sa dérivée. Les modules d’intégration de Scipy (et plus précisément odeint) permettent de trouver y et, en prenant un peu d’avance sur l’affichage (cf. section 2.4), on peut tracer la fonction résultat. Le code 10 propose une solution à ce problème. # −∗− c o d i n g : u t f −8 −∗− import numpy a s np from s c i p y . i n t e g r a t e import o d e i n t import m a t p l o t l i b . p y p l o t a s p l t #d é r i v é e de y ( en t a n t que t a b l e a u : y [ 0 ] e s t l a f o n c t i o n , y [ 1 ] l a d é r i v é e ) def d e r i v ( y , t ) : a = −2.0 b = −0.1 return np . a r r a y ( [ y [ 1 ] , a ∗y [ 0 ] + b∗y [ 1 ] ] ) t p s = np . l i n s p a c e ( 0 . 0 , 1 0 . 0 , 1 0 0 0 ) #v a l e u r s i n i t i a l e s de y e t de s a d é r i v é e y i n i t = np . a r r a y ( [ 0 . 0 0 0 5 , 0 . 2 ] ) y = odeint ( deriv , yinit , tps ) plt . figure () p l t . p l o t ( tps , y [ : , 0 ] ) p l t . x l a b e l ( ’t ’ ) p l t . y l a b e l ( ’y ’ ) p l t . show ( ) Listing 10 – Résolution par intégration d’une équation différentielle ordinaire en utilisant Spicy 12 2.3.3 Interpolation Scipy possède un module d’interpolation assez complet, qui comprend plusieurs méthodes d’interpolation définies sous formes de classes. Il est possible d’utiliser des interpolations linéaire ou cubique par exemple. Le code 11 montre quelques appels de ces méthodes. Notons qu’il est nécessaire d’instancier la classe pour l’utiliser. La figure 1 présente le résultat 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 ( ) Listing 11 – interpolation par plusieurs méthodes disponibles dans Spicy 2.4 Quelques exemples de Matplotlib Le module Matplotlib, comme son nom l’indique, s’occupe du tracé graphique. Nous avons déjà vu un exemple d’utilisation de ce module dans la partie interpolation. Le code 12 et la figure 2 donnent de nouveaux exemples, en illustrant certaines possibilités (titres, labels, types de courbes, couleurs...), tandis que le code 13 et la figure 3 démontrent qu’il est possible d’afficher simultanément plusieurs graphes sur une même figure. 13 Figure 1 – Tracé des interpolants # −∗− c o d i n g : u t f −8 −∗− import m a t p l o t l i b . p y p l o t a s p l t import numpy a s np 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 ( ) Listing 12 – Quelques possibilités de base de matplotlib 14 Figure 2 – résultat du code 12 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 def f ( t ) : return np . exp(− t ) ∗ np . c o s ( 2 ∗ np . p i ∗ t ) def g ( t ) : return np . exp ( t ) ∗ np . s i n ( 2 ∗ np . p i ∗ t ) def h ( t ) : return np . c o s ( 2 ∗ np . p i ∗ t ) ∗∗3 t 1 = np . a r a n g e ( 0 . 0 , 5 . 0 , 0 . 1 ) t 2 = np . a r a n g e ( 0 . 0 , 5 . 0 , 0 . 0 2 ) plt . figure (1) plt plt plt plt plt . . . . . 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 Figure 3 – résultat du code 13 Toutes les courbes peuvent bien sur être tracées avec le module matplotlib. Le code 14 et la figure 4 donnent quelques exemples de courbes paramétrées classiques. 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 ) plt . figure (1) plt . subplot (221) p l t . p l o t ( [ 3 + 1 . 5 ∗ c o s ( t ) ∗(1+ c o s ( t ) ) f o r t in l t ] , [ s i n ( t ) ∗(1+ c o s ( t ) ) f o r t in l t ] , ’g ^ ’) p l t . t i t l e ( " Cardioide " ) plt . subplot (222) p l t . p l o t ( [ c o s ( t ) ∗∗3 f o r t in l t ] , [ s i n ( t ) ∗∗3 f o r t in l t ] , ’k ’ ) p l t . t i t l e ( " Astroide " ) plt . subplot (223) l t = np . l i n s p a c e ( 0 , 1 0 ∗ pi , 1 0 0 ) p l t . p l o t ( [ 3 ∗ ( t−s i n ( t ) ) f o r t in l t ] , [3∗(1 − c o s ( t ) ) f o r t in l t ] , ’r ’ ) p l t . t i t l e ( " cycloide " ) plt . subplot (224) l t = np . l i n s p a c e ( 0 , 2 ∗ pi , 1 0 0 ) p l t . p l o t ( [ 2 ∗ s i n ( t ) ∗∗2∗ c o s ( t ) f o r t in l t ] , [ 2 ∗ s i n ( t ) ∗ c o s ( t ) ∗∗2 f o r t in l t ] , ’g - ’ ) p l t . t i t l e ( " quadrifolium " ) p l t . show ( ) Listing 14 – Quelques courbes paramétrées 17 Figure 4 – résultat du code 14 18
Documents pareils
Bibliothèques scientifiques de Python : une introduction
Distribué sous la licence CC BY-SA 3.0 FR
http://creativecommons.org/licenses/by-sa/3.0/fr/
Python pour les mathématiques numériques et l
Optimization and root finding (scipy.optimize)
Interpolation (scipy.interpolate)
Fourier Transforms (scipy.fftpack)
Signal Processing (scipy.signal)
Linear Algebra (scipy.linalg)
Sparse Eigenvalue ...
Introduction à Python
sqrt(9) #utilisation de la fonction sqrt importée (sans avoir besoin de préciser math.)
from math import * #importation de toutes les fonctions de la bibliothèque math
#on peut alors appeler toutes...