[PDF] [PDF] Introduction à Numpy et Scipy - PCSI, Lycée Kléber

integrate # Intégration de fonctions ou d'équadiffs 4 import scipy optimize # Zéros et ajustements de fonction 5



Previous PDF Next PDF





[PDF] Introduction à Numpy et Scipy - PCSI, Lycée Kléber

integrate # Intégration de fonctions ou d'équadiffs 4 import scipy optimize # Zéros et ajustements de fonction 5



[PDF] Mathématiques et Python - Apprendre-en-lignenet

This allows NumPy to seamlessly and speedily integrate with a wide variety of databases Scipy est un ensemble qui comprend de nombreux modules utiles 



[PDF] Python-AN - concours Centrale-Supélec

15 mai 2017 · import numpy as np import scipy optimize as resol import scipy integrate as integr import matplotlib pyplot as plt Nombres complexes Python 



[PDF] Intermediate Python: Using NumPy, SciPy and Matplotlib

Numerical Integration • scipy integrate is a module that contains functions for integration • Integration can be performed on a function defined by a lambda



[PDF] INTEGRALS and DERIVATIVES

import scipy integrate as integrate import numpy as np import math # Either we define the function like this def func(x): return x ** 3 sol=integrate quad(func, 0, 1)



[PDF] Informatique Introduction à Scipy Python scientifique Scipy

scipy stats statistiques Quelques sous-modules de scipy Intégration Il existe from scipy import integrate la fonction utilisée est scipy integrate quad()



[PDF] TD: Intégrale multiple - ISEN-Brest

3 Code avec Python # -*- coding: utf-8 -*- import math import sympy import scipy as sp import numpy as np import matplotlib pyplot as plt from numpy import 



[PDF] SciPy Reference Guide - Numpy and Scipy Documentation - SciPyorg

20 fév 2016 · SciPy Reference Guide, Release 0 17 0 quadrature -- Integrate with given tolerance using Gaussian quadrature romberg -- Integrate func 



Numerical Computing in Python

Perform the necessary modifications such that the function works for both scalar types and NumPy arrays Exercise 4 5 Vectorize a numerical integration rule The 



[PDF] lektion3

24 oct 2019 · 6 Integration - uneigentliche Integrale 7 Bestimmte Integrale 1 Lektion 3 1 1 Python Funktionen 1 4 Lamdifizierung (sympy -> numpy/scipy)

[PDF] integrale d'ito

[PDF] intégrale d'un signal triangulaire

[PDF] intégrale de lebesgue cours

[PDF] integrale de riemann exercices corrigés pdf

[PDF] integrale fonction dirac

[PDF] intégrale généralisée exercice corrigé pdf

[PDF] intégrale méthode des rectangles

[PDF] intégrale méthode des trapèzes

[PDF] integrale python

[PDF] intégrale sinus cardinal

[PDF] intégrale stochastique mouvement brownien

[PDF] integrale stochastique pdf

[PDF] intégralité définition

[PDF] integrate python

[PDF] integrated agriculture

INS1

IntroductionàNumpyetScipy

Labase àimporter(pas nécessairement tousensembles,maistousv ontservirda nscechapitre).

PartieI

Overview

1Numpy

NumPyisthefun dament alpackag eforscientificcomputingwithPython.I tcontainsamongother things: -apowerfulN-dimensionalarrayobject -sophisticated(broadcasting)functions -toolsforintegra tingC/C++a ndFortrancode -usefullinear algebra,Fo uriertransform,andrandomnum bercapabilities Besidesitsobviousscie ntificuse s,NumPycanalsobeuseda sane cientmulti-dime nsionalcontainerof genericdata.Arbitrar ydata-typescan bedefined.ThisallowsNumPytosea mlesslyandspeedilyintegrate withawidev ari etyofdata bases. Numpyislicensed undert heBSDlicense,enablingre usewithfewrestr ictions.

2Scipy

SciPyandfrien dscanbeus edforavarietyoftasks :

-NumPy'sarraytypeau gmentsthePython languagewitha ne!cientdatastruc tureusefulfo r numericalwork,e.g.,manipul atingmatrices. NumPyalsoprovide sbasicnumericalroutines,suchas toolsforfindingeigenv ectors. -SciPycontain sadditionalroutinesneed edinscientificwork:forexample, routinesforcomputing integralsnumerically,solvi ngdi erentialequations,optimi zation,andsparsematrices. -Themat plotlibmoduleproduceshighqual ityplots.Withityo ucanturnyourdataoryourmo dels intofiguresfor presentationsor articles.Noneedtodo thenumericalworkinonepro gram,save the data,andplotitwi thanothe rprogram. 1

EBougnol,JJFleck,

MHeckmann&MKostyra,

Kléber,PCSI!&"#$!%-#$!&I.Overview2/24

-UsingIPythonmak esinteractivework easy.Dataproces sing,explorationofnumericalmode ls,trying outopera tionson-the-flyallowstogoquickl yfromanideatoaresult.Seeth eIPythonsiteform any examples. -Thereisasizea blecol lec tionofbothgenericandapp lication-specificnumericalands cient ificcode, writtenusingPython, NumpyandScipy. Don'treinventthewhe el,theremayalr eadybeapr e-made solutionfory ourproblem.See TopicalSoftwarefor apartiallist. -AsPyth onisapopulargen eral-p ur poseprogramminglangua ge,ithasmanyadvancedmodulesfor buildingforexampleinter activeap plications(seee.g.wxPyt honandTraits)orwebsites(seee.g. Django).UsingSciPywiththe seisaquickwayto buildafully -fledgedsc ientificapplica tion.

3Trouverdel'aide

Plusieursméthodesexisten tpourtrouverdeladocumen tationsurlesfonctionsch erchées: Surin ternet:http://numpy.orgethttp://scipy.orgpeuventêtredebonspoin tsdedépart. Voirau ssi http://docs.scipy.org Viahelp():Commed'habit ude,touteslesaidesinternesauxfon ctionsetobjetsman ipulésson tdisponibles vialacomma ndehelp(),parexemplehelp(numpy)ouhelp(numpy.trapz). Vianp.info():alemêmecomportementquehelp()maisnerentrepa sdans unéditeur:ila!chedirec- tementl'aidesurl'écra n(oul'imprimeda nsunfic hier,pourplusde détails,voirnp.info(np.info)). Vianp.lookfor():Permetderegarder dansle sfichiersd'aidelesoccuren cesdelachaîn edecaract ère donnéeenargumen t.

1>>>importnumpyasnp

2>>>np.lookfor('determinant')

3Searchresultsfor 'determinant'

4--------------------------------

5numpy.linalg.det

6Computethedeterminant ofanarray.

7numpy.linalg.slogdet

8Computethesign and(natural)logarithm ofth edeterminant ofanarr ay.

9numpy.vander

10GenerateaVandermonde matrix.

11numpy.linalg.qr

12Computetheqr factorizationof am atrix.

13numpy.ma.vander

14GenerateaVandermonde matrix.

15numpy.linalg._umath_linalg.slogdet

16slogdetont helasttwo dimensionsandbroadcaston therest.

Vianp.source():Permetderegarder lecode sourced'unefonctiondonn ée.Part iculièrement utilepour compareretcomprendrel'i mpléme ntationdesdi

érentsalgorithmes.

1>>>importnumpyasnp

2>>>np.source(np.identity)

3Infile:/op t/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3. 3/site-packages/numpy/core/numeric.py

4

5defidentity(n,dtype=None):

6"""

7Returntheidentity array.

8

EBougnol,JJFleck,

MHeckmann&MKostyra,

Kléber,PCSI!&"#$!%-#$!&II.Fonctionsouobjetsutilesde Numpy3/24

9Theidentityarray isasquare arraywith oneson

10themaindi agonal.

11

12Parameters

13----------

14n:int

15Numberofrow s(andcolumns) in!n!x!n!output.

16dtype:dat a-type,optional

17Data-typeofthe output.Defaultst o!!float!!.

18

19Returns

20-------

21out:ndarr ay

22!n!x!n!arraywithits maindiagonalset toone,

23andallother elements0.

24

25Examples

26--------

27>>>np.identity(3)

28array([[1.,0., 0.],

29[0.,1.,0. ],

30[0.,0.,1.] ])

31
32"""

33fromnumpyi mporteye

34returneye(n,dtype=dtype)

PartieII

FonctionsouobjetsutilesdeNumpy

1np.array,np.arange,np.reshape

Pourcréerd estableauxdeno mbressurl esquelslescalculspeuventê trepar ticulièremente caceset rapides(carcodésenC).P ermettraaus sitoutlecalcul matric ielpar lasuitesibesoin. >>>importnumpyasnp >>>np.array([1,2,3])#Untableaud'entiers array([1,2, 3]) array([1.,2., 3.]) array([[1,2], [3,4]]) array([1.+0.j,2.+0.j, 3.+0.j]) array([[1,2], [3,4]])

EBougnol,JJFleck,

MHeckmann&MKostyra,

Kléber,PCSI!&"#$!%-#$!&II.Fonctionsouobjetsutilesde Numpy4/24 array([1,3,5]) array([[0,1, 2,3, 4], [5,6,7 ,8,9], [10,11,12, 13,14], [15,16,17, 18,19], [20,21, 22,23,24]]) Attention:ilfaut seméfierdel'opéra teur +=avecdesnp.arraycara+=0.1n'aurapaslemêmee"et sil'array anecon tientquedesentiersous'i lcontient desentier ssousformedeflottants .Enreva nche, a=a+0.1donneratoujoursle résultatvoulu.

2np.linspace,np.trapz

np.linspace(a,b,N):permetdedistribu erNpoin tsrégulièrementespacés 1 surunin tervalle[a;b](binclus pourunefo is!Peut-ê treexclusibes oi nparl'argumentoptionnelendpoint=False).Sil'a rgument optionnelretstep=Trueestdonné,alors renvoie lalargeurdes intervallesenplusdutableaude points.

np.trapz(fx,x):permetdefairel'i ntégra tionparméthode destrapèzesqu'onaimplémentédansle

chapitreprécédentàpar tird'unesériefxdesva leursd'unefonctionpriseendesp oints x.Letableau

xestoptionnel,on peutaussi définirlav aleurdx=hsilesp ointsson ttousespacésd'unelargeurh fixée.

1defintegration_trapz_n(f,a,b,n=100):

2'''Retoursurl'intégration parmé thodedestrapèzes endélégant toutle

3travailàn p.trapz().Rappel: nestlenombred'intervalles etnonle

4nombredep oints(cfpb clôtures/piquets)'''

6x_arr=np.linspace(a,b,n+1)

12returnnp.trapz(fx_arr,x_arr)

3Utilisationdenp.matrix

Laclasse desmatrices,permetde fairedu calculmatriciel

1>>>importnumpyasnp

3>>>A#LamatriceA,

4matrix([[0,1,2],

5[3,4,5],

6[6,7,8]])

7>>>A**2#soncarrématriciel,

8matrix([[15,18, 21],

1 Ilau np etitco painnp.logspace()quifaitlamê mechosemais sur uneéc hellelogarithmique.

EBougnol,JJFleck,

MHeckmann&MKostyra,

Kléber,PCSI!&"#$!%-#$!&III.Fonctionsouobjetsutilesde Scipy5/24

9[42,54,66] ,

10[69,90,11 1]])

11>>>A.transpose()#satransposée,

12matrix([[0,3,6],

13[1,4,7],

14[2,5,8]])

16matrix([[5, 14,23],

17[14,50,86] ,

18[23,86,14 9]])

20matrix([[204]])

22204

PartieIII

FonctionsouobjetsutilesdeScipy

1Sous-modules

Chacundessous-m odules(sous_modulepourl'exem ple)s'importeselonlasyntaxe importscipy.sous_module Voicilaliste( parord realphabétique )deceuxquipo urront(apriori )vousêtreutiles. constants|Constantes physiquesoumathémat iques fftpack|Routines deFFT(Transformation deFourierR apide) integrate|Integration etrésolution d'équationsdifférentielles ordinaires interpolate|Routines d'interpolationetdelissage (smoothingsplines ) linalg|Algèbre linéaire ndimage|Traitement d'imagesàN dimensions optimize| Routinesd'optimisationetderecherche deracines signal|Traitemen tdusignal stats|Fonctions etdistributions statistiques Celuiqu'onuti liseraleplusda nscecoursestbiensûrscipy.integrate.

2Intégrationnumérique

a)Cal culsd'intégrales

Plusieursméthodesd'intég rationdi

érentesexistentselon lesusagesattendus.

MethodsforI ntegratingFunctions givenfunctionobject. quad--General purposeintegration. dblquad--General purposedouble integration. tplquad--General purposetriple integration. fixed_quad--Integra tefunc(x)using Gaussianquadratureofordern. quadrature--Integra tewithgiven toleranceusingGaussianquadrature. romberg--Integrate funcusing Rombergintegration.

EBougnol,JJFleck,

MHeckmann&MKostyra,

Kléber,PCSI!&"#$!%-#$!&III.Fonctionsouobjetsutilesde Scipy6/24 MethodsforI ntegratingFunctions givenfixedsamples. trapz--Use trapezoidalru letocompute integralfromsamples. cumtrapz--Use trapezoidalruleto cumulativelycomp uteintegral. simps--Use Simpson'sruletocomputeintegralfromsamples. romb--Use RombergIntegrationto computeintegr alfrom (2**k+1) evenly-spacedsamples. Seethespec ialmodule'sorthogonalpolynomials(special)forGaussian quadraturerootsand weightsfor otherweightingfactors andregions.

Interfacetonumerical integratorso fODEsystems.

odeint--General integrationof ordinarydifferential equations. ode--Integrate ODEusing VODEandZ VODEroutines. Sil'on disposed'un échantillonnagede lafonction: np.trapz(fx,x):onl' adéjàvudansN umpy(et onpeutaussi l'appelerselon sp.trapz(fx,x)ou sp.integrate.trapz(fx,x)).Conna issantunéchantillonnagefxdelafo nctionà intégrersurun ensemblexdepo ints,ellerenvoielavaleurde l'intégra levialaméthodedestrapèzes. sp.integrate.cumtrapz(fx,x):faitlamême choseque np.trapz(fx,x)saufqu'ilren voieun tableau

contenantlesvaleurscumuléesde l'intégraleaprès chaquepoint.L'in tégraletotaleseretrouve don c

dansledern ierélémen tdutableau.Peutêtreutileenstatistiques pourlescalculs d'e ectifscumulés.

Attention:pardéfaut,letable audesorti eaunélémentdemoinsque letabl eaud'entrée,maisonpe ut

donnerlapremièreva leur(po urav oircorrespondancedes indicesdesdeuxtableaux)vial'a rgument optionnelinitial=0. sp.integrate.simps(fx,x):Connaissantunéchantillonnagefxdelafo nctionà intégrersurunensemble xdepo ints,ellerenvoielavaleurde l'intég ralevialaméthodedeSimpsonquirevien tàa pproximer lacourb eparuneparabolesur troispoints consécutifs.

sp.integrate.romb(fx,dx):IntégrationparméthodedeRomberg( méthode destrapèzes"améliorée »à

l'aidedeDL,cfpages urwiki pédia).Ne marche ques'ilyaun nombredep ointsd'échantillonnages

égalà2

n +1(donc2 n intervallesélémentairesd'intégratio n).Attention,contrairemen tauxprécédents, ilfaut fournirlalargeur dxdesinterv alles(carelledoitresterfixepour quelaméthodema rche)

1>>>importscipyassp

2>>>importscipy.integrate

3>>>#Pointsd'échantillonnage.

84.04

104.0400000000000009

12array([8.00000000e-04, 8.00000000e-03,3.60000000e-02,

154.04000000e+00])

EBougnol,JJFleck,

MHeckmann&MKostyra,

Kléber,PCSI!&"#$!%-#$!&III.Fonctionsouobjetsutilesde Scipy7/24 174.0

20>>>fxromb=[xi**3forxiinxromb]

23>>>sp.integrate.romb(fxromb,dx=dxromb)

244.0
Sil'on veutintégrer directementunefonction sansavoiràpasser parlaphase d'échan tillonnage: sp.integrate.quad(f,a,b):intègrelafonctionf(x)surl'interv alle[a;b].Renvoieundoubletconte- nantlavaleurdel'in tégrale etuneestimationdel'erreurmaxima leco mmiselorsdel'intégration. Silafo nctionfprendplusde uneva riable,les valeurs desautrespeuventêtrespécifiéesvia l'ar- argumentdelafonction.

1>>>frommathimportexp

2>>>importscipyassp

3>>>importscipy.integrate

4>>>deff(x,y,z):returnexp(-x)*y*z**2

5...

6>>>g=lambdax:f(x,1,2)

8>>>sp.integrate.quad(g,0,float('inf'))

sp.integrate.dblquad(f,a,b,g,h):intègrelafonctionf(x,y)enxsurl'interv alle[a;b]etenysur

l'erreurma ximalecommiselorsdel'intég ration.Attentio n,lapremièrevaria blexd'intégrationest

toujourslepremierargument delafo nctionet ladeuxièmevariableytoujoursladeuxième.Attentio n

(bis),gethdoiventêtre"callable»,c'est- à-dire accepterun argument(enl'occurencex).Siles born es

d'intégrationenysontfixes,onpourra utiliserdes "fonctionsa nonymes»comme dansl'exemple ci-dessous.

1>>>importscipyassp

2>>>importscipy.integrate

3>>>deff(x,y):returnx**2*y

4... sp.integrate.tplquad(f,a,b,g,h,r,q):intègrelafonctionf(x,y,z)enxsurl'in tervalle[a;b],eny surl'interv alle[g(x);h(x)]etenzsurl'interv alle[r(x,y);q(x,y)].Renvoieundoubletcontenantla valeurdel'intégr aleetu neestimationdel'erreurmaximalec ommise lorsdel'i ntégration.Attention, lapremièrev ariable xd'intégrationesttoujourslepremierargumen tdela fonction,ladeuxième variableytoujoursladeuxièmeetlatro isièmeztoujourslatroisième.Atten tion(bis), gethdoivent être"callable »àun argument( x)etretqdoiventêtre"callable»àdeux argumen t(x,y).

EBougnol,JJFleck,

MHeckmann&MKostyra,

Kléber,PCSI!&"#$!%-#$!&III.Fonctionsouobjetsutilesde Scipy8/24

1>>>frommathimportsqrt,pi

2>>>importscipyassp

3>>>importscipy.integrate

5>>>R=1

6>>>f=lambdax,y,z:1

7>>>g=lambdax:0

8>>>h=lambdax:sqrt(R**2-x**2)

9>>>r=lambdax,y:0

10>>>q=lambdax,y:sqrt(R **2-x**2-y**2)

141.0471975511965976

b)Résol utiond'équationdi

érentielle

C'estlaprocéd ureodeint(f,y0,t)qu'ilfaut utiliserpourintég rernumériquemen tuneéquation di

érentielledutype

dy dt =f(y,t)

oùla "fonctioni nconn ue»ypeutêtreun tableaudefon ction sinconnues(cequipermet deréso udresoit

unsystèmed'équa tionsco uplées,soituneéquationd'o rdresupérieurv uecommeunsystème d'équations

dupremiero rdreco uplées).y0estlaliste desconditionsinitiales (pour chaqueélémen tdutableau y)

àl'instantt[0],ettreprésentel'ensembledestempsa uquelsontveutquel'équationdi"érentiellesoit

résolue.Voiciles exemplesquivontêtretraités parla suite(les deuxderniers servirontpourlaprésentation

deMatpl otlib): dx dt x (1) dx 1 dt =!kx 2 dx 2 dt =!kx 1 (2)

¨x+2"˙x+#

0 2 x=0quis'écrit dx dt =˙x d˙x dt =!2"˙x!# 0 2 x (3)

¨x+2"˙x+#

0 2 x=Acos#tquis'écrit dx dt =˙x d˙x dt =!2"˙x!# 0 2 x+Acos#t (4)

EBougnol,JJFleck,

MHeckmann&MKostyra,

Kléber,PCSI!&"#$!%-#$!&III.Fonctionsouobjetsutilesde Scipy9/24

¨x+$¨x+2"˙x+#

0 2 x=0quis'écrit dx dt =˙x d˙x dt =¨x d¨x dtquotesdbs_dbs22.pdfusesText_28