• Aucun résultat trouvé

[PDF] Formation approfondie sur les mathématiques et le langage Python | Cours informatique

N/A
N/A
Protected

Academic year: 2021

Partager "[PDF] Formation approfondie sur les mathématiques et le langage Python | Cours informatique"

Copied!
18
0
0

Texte intégral

(1)

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 modulepylabintè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...)

(2)

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 la valeur de I =Rb

af (x)dx, en utilisant trois méthodes classiques : – la méthode des rectangles :I ≈

n−1 X i=0 (xi+1− xi)f  xi+ xi+1 2 

– la méthode des trapèzes : I ≈ h " f (a)+f (b) 2 + n−1 X i=1 f (xi) # – la méthode de Simpson : I ≈ h6 " f (a) + f (b) + 4 n−1 X i=0 f (x2i+1) + 2 n−1 X i=1 f (x2i) # avec h = b−an et xk= a + kh2

et où (x0· · · xn) est une subdivision régulière de l’intervalle [a, b] de pas h

(3)

 # −∗− 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 ) ∗ ( x j −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 ∗ ( x j −x i ) return S def s i m p s o n ( 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+= ( x j −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 r e c t a n g l e s : " , r e c t a n g l e s ( f n , 0 . , 5 . , 1 0 0 ) ; print " par t r a p è z e s : " , t r a p e z e s ( f n , 0 . , 5 . , 1 0 0 ) ; print " par S i m p s o n : " , s i m p s o n ( f n , 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+

√ 5 2 .

(4)

 # −∗− 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 a b s ( ( a /b ) −(1+5∗∗0.5) / 2 ) return b def main ( ) : f i b o n a c c i ( 3 0 ) 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 f o n c t i o n ne s ’ ’ annu le pas dans l ’ ’ i n t e r v a l l e [ ’+s t r ( a )+’ , ’+s t r ( b ) +’] ’ )

return 0

while( a b s ( a−b )>1e −3) :

m=(a+b ) / 2 . print m i f f (m) ∗ f ( a ) >0: a=m e l s e: b=m print( ’ la s o l u t i o n de f ( x ) =0 est ’+s t r (m) ) return m print( z e r o ( f , − 1 0 . , 1 0 . ) )  

(5)

Exercice 3 Produire un code qui calcule le zéro d’une fonction en utilisant la méthode de Newton (algorithme1) :

Algorithm 1: Méthode de Newton Entrées: N, , f, fp, x0 n← 0 xn ← x0 répéter xn ← xn− f (xn) fp(xn) n ← n + 1 si fp(xn) <  alors Division par zero fin jusqu’à f (xn) fp(xn) <  OU n > N ;

Exercice 4 Calculer une approximation de π en utilisant par exemple les deux résultats classiques : π2 6 = ∞ X n=1 1 n2 et π 2 = ∞ X n=1 4n2 4n2− 1

2

... 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 ri-valing 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 in-tegrating C/C++ and Fortran code

(6)

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional contai-ner of gecontai-neric 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.

(7)

 # −∗− 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 # I d e n t i t é i = np . e y e ( 5 ) print i # M a t r i c e 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, multipli-cation par un scalaire, produit matriciel...Le code5présente quelques exemples de ces opérations.

(8)

 # −∗− 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 . ] , f l o a t ) # a d d i t i o n 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 p a r 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 t erm e à t erm e

D4 = np . d o t (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 . d o t (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 . k r o n (A, B)#p r o d u i t de K r o n e c k e r #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

(9)

 # −∗− 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 . ] , f l o a t ) #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 . r a n k (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 p=1 a2kp !2 pour i ∈ {k + 1 · · · n} faire aik← a1 kk aik− k−1 X p=1 aipakp ! fin fin

Notons que numPy propose de nombreux autres atouts, que nous vous conseillons de décou-vrir 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 :

(10)



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, u s e d 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 c u s t o m a r y form in c o d e ( s e e Examples ) .

P a r a m e t e r s : 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 , w h e r e a 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 : b o o l , 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 . v a r i a b l e : s t r , o p t i o n a l

Changes t h e v a r i a b l e u s e d 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 C o n s t r u c t t h e p o l y n o m i a l : >>> 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 E v a l u a t e t h e p o l y n o m i a l a t : >>> p ( 0 . 5 ) 4 . 2 5 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 a r r a y ( [ 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−t h 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

r e m a i n d e r ) : >>> p ∗ p p o l y 1 d ( [ 1 , 4 , 1 0 , 1 2 , 9 ] ) >>> ( p ∗∗3 + 4 ) / p ( p o l y 1 d ( [ 1 . , 4 . , 1 0 . , 1 2 . , 9 . ] ) , p o l y 1 d ( [ 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 u s e d in a l l f u n c t i o n s t h a t a c c e p t a r r a y s :  

(11)

 >>> p ∗∗2 # s q u a r e o f p o l y n o m i a l p o l y 1 d ( [ 1 , 4 , 1 0 , 1 2 , 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 a r r a y ( [ 1 , 4 , 9 ] ) The v a r i a b l e u s e d 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 p a r a m e t e r : >>> 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 ] ) T h i s 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 ] ) A t t r i b u t e s c o e f f s o r d e r v a r i a b l e Methods __call__ ( v a l ) d e r i v ( [m] ) 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 . i n t e g ( [ m, k ] ) 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)

(12)



# −∗− 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 S c i p y : " , i n t e g r a t e . quad ( f n , 0 , 5 )

print " R o m b e r g par S c i p y : " , i n t e g r a t e . romberg ( f n , 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 p a r p a s r é g u l i e r x = l i n s p a c e ( 0 , 5 , 1 0 0 0 ) y=f n ( x ) print " t r a p e z e s par S p i c y " , 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

On souhaite par exemple résoudre l’équation différentielle ddt22y = 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. section2.4), on peut tracer la fonction résultat. Le code 10propose 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 = o d e i n t ( d e r i v , y i n i t , t p s ) p l t . f i g u r e ( ) p l t . p l o t ( t p s , 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 ( )  

(13)

2.3.3 Interpolation

Scipy possède un module d’interpolation assez complet, qui comprend plusieurs méthodes d’in-terpolation définies sous formes de classes. Il est possible d’utiliser des ind’in-terpolations linéaire ou cubique par exemple. Le code11montre quelques appels de ces méthodes. Notons qu’il est néces-saire 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 s p 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 . t a n ( 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 ’ ) i n t e r p _ q u a d = i n t e r p 1 d ( x_measure , y_measure , k i n d=’ q u a d r a t i c ’ ) # 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 = i n t e r p _ q u a d ( 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 _ i n t _ l i n , ’ - ’ , x_computed , y_int_cub , ’ - - ’ , x_computed , y_int_quad , ’* ’ )

p l t . l e g e n d ( [ ’ data ’ , ’ l inear ’ , ’ 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

figure2donnent de nouveaux exemples, en illustrant certaines possibilités (titres, labels, types de courbes, couleurs...), tandis que le code 13 et la figure3 démontrent qu’il est possible d’afficher simultanément plusieurs graphes sur une même figure.

(14)

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 ( " A b c i s s e s " ) p l t . y l a b e l ( ’ f o n c t i o n s ’ )

p l t . l e g e n d ( [ ’ c ourbe 1 ’ , ’ c ourbe 2 ’ , ’ courbe 3 ’ ] , l o c=’ best ’ ) p l t . t i t l e ( " Z o u l i e s c o u r b e s " )

p l t . show ( )

 

(15)

Figure 2 – résultat du code12  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 ) p l t . f i g u r e ( 1 ) p l t . s u b p l o t ( 2 2 1 ) p l t . x l a b e l ( " A b c i s s e s " ) p l t . p l o t ( t1 , f ( t 1 ) , ’ bo ’ , t2 , f ( t 2 ) , ’k ’ ) p l t . x l a b e l ( " A b c i s s e s " ) p l t . y l a b e l ( " f " ) p l t . s u b p l o t ( 2 2 2 ) p l t . p l o t ( t2 , g ( t 2 ) , ’r - - ’ ) p l t . x l a b e l ( " A b c i s s e s " ) p l t . y l a b e l ( " g " ) p l t . s u b p l o t ( 2 2 3 ) p l t . p l o t ( t1 , h ( t 1 ) , ’b - ’ ) p l t . x l a b e l ( " A b c i s s e s " ) p l t . y l a b e l ( " h " ) 15

(16)

Figure 3 – résultat du code13

Toutes les courbes peuvent bien sur être tracées avec le module matplotlib. Le code14 et la figure4donnent quelques exemples de courbes paramétrées classiques.

(17)



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 ∗ p i , 1 0 0 ) p l t . f i g u r e ( 1 ) p l t . s u b p l o t ( 2 2 1 ) 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 ( " C a r d i o i d e " ) p l t . s u b p l o t ( 2 2 2 ) 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 ( " A s t r o i d e " ) p l t . s u b p l o t ( 2 2 3 ) l t = np . l i n s p a c e ( 0 , 1 0 ∗ p i , 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 ( " c y c l o i d e " ) p l t . s u b p l o t ( 2 2 4 ) l t = np . l i n s p a c e ( 0 , 2 ∗ p i , 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 ( " q u a d r i f o l i u m " ) p l t . show ( )  

(18)

Figure

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
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
Figure 3 – résultat du code 13
Figure 4 – résultat du code 14

Références

Documents relatifs

through RANSAC algorithm; (lower left) detection of the non-occluded parts of the tomato, ω i t +1 , through region growing algorithm; (lower right) initialization of the

It means that, even though in theory, we can partly understand that SVC should be better than AVC with its scalability feature at the encoding step, but it is only through

La seconde partie de cette thèse s'attache à construire un mécanisme de régula- tion qui minimise le dommage lié à la dégradation de la qualité de l'eau, maintienne une activité

Ce que manifeste enfin la confrontation des jugements portés par les voyageurs du XVII e siècle sur les différentes langues orientales, c’est la manière dont

Cette étude exploratoire examine par quel processus, dans le cadre d’un projet d’exploitation d’une mine de nickel, une entreprise française fait

Or en 2004-2005, pour la première fois depuis 1992, les États-Unis plaident fortement en faveur d’une importante opération de paix (de dix mille hommes) dans un conflit africain,

Observações sobre a ocorrência da vespa de Uganda Prorops nasuta Waterston em lavouras da Zona da Mata, infestadas pela broca do café Hypothenemus hampei (Ferrari, 1867).. In:

Mais surtout, il n’est pas le fait de quelques chercheurs qui auraient choisi d’être plus progressistes que d’autres : cette discussion, scientifiquement nécessaire, nous