Vous êtes sur la page 1sur 61

Licence MIASH 2023/2024

Introduction à Python
18h+18h
Texte
Roland Becker
roland.becker@univ-pau.fr
Partie 1 : Pourquoi apprendre python

Partie 2 : Les bases du langage

Partie 3 : Algorithmique

Partie 4 : L’environnement python

Partie 5 : Graphisme matplotlib

Partie 6 : Langage avancé


Partie 7 : Algèbre linéaire : numpy
P 1 : Pourquoi apprendre python
✤ Interaction avec un ordinateur
✤ Intuitif
✤ Pas de compilation
✤ Accès à beaucoup d’outils extérieurs
✤ Portable 1 développement programme

✤ Gratuit 2 environnement programmation


Quelques ressources: 3 pratique
• python.org
4 premier exemple
• numpy.org

• https://python.sdv.univ-paris-diderot.fr/cours-python.pdf

• https://www.inforef.be/swi/download/apprendre_python3_5.pdf

• https://perso.limsi.fr/pointal/_media/python:cours:courspython3.pdf
Développement d’un programme

✤ Choix des outils


✤ Écriture du programme
✤ Validation du programme
✤ Test du programme
✤ Simulation
✤ Analyse des donnée
✤ Représentation des résultats
Environnement programmation

✤ Utilisation dans une ‘shell’


✤ Éditeur - exécution interpréteur

✤ Spyder, pycharm,.. script/fichier

aide
éditeur

interpréteur
D’un point de vue pratique

✤ Apprendre à utiliser son clavier


✤ Nous utilisons : () ,[], {}, #, …
✤ Un peu de vocabulaire :

file fichier text, image, program, ascii/binary


directory/folder repertoire/classeur contient files and folders
shell ligne de commande communication human-computer
processor processeur performs operations on files
screen/keyboard écran/terminal
bit/byte bit/octet byte=8 bit
program/code programme sequence of instructions written in a file
Un exemple

>>> import numpy as np

>>> import matplotlib.pyplot as plt

>>> from scipy import integrate

>>> def pend(y, t): # we define the pendulum

>>> alpha, goL = 0.05, 5.0

>>> theta, omega = y

>>> return [omega, -alpha * omega - goL * np.sin(theta)]

>>> y0 = [0.8*np.pi, 0.0] # initial angles

Attention : >>> t = np.linspace(0, 10, 100) # integration interval

>>> sol = integrate.odeint(pend, y0, t) # use scipy


indentation
>>> plt.plot(t, sol[:, 0], 'b', label='theta(t)') # plot

deux-points >>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')

>>> plt.legend()

>>> plt.show()
Programming

✤ Programming demands significantly higher standard of accuracy.


Things don’t simply have to make sense to another human being,
they must make sense to a computer. Donald Knuth, 1938-.

✤ PEP 8 - Style Guide for Python Code : https://www.python.org/


dev/peps/pep-0008

✤ Choix des noms de variables

✤ Similar to the mathematical description of the problem (lower case)

✤ Variables without mathematical definition: use a carefully chosen


descriptive name

✤ Similar rules for names of functions, classes (but upper case !), and files
P2 : Les bases du langage
✤ Principes du langage
✤ Structures de données simple
✤ Conditions
✤ Boucles
✤ Help!
✤ Structure de données avancées
✤ Mots réservés
Utilisation spyder
Ligne de commande/python
shell
• pour aller vite
• tester petit éléments
• pas pratique (indentation)
• pas de traces

fichiers
• éditeur de programme !
• exécution simple
• gestion des fichiers
exemple fichier main.py
Principes du langage

✤ Pas de compilation
✤ Pas de déclarations
✤ Indentation :
✤ Signe =

>>> s = input("Entrez un nombre")


>>> type(s)
>>> sf = float(s)
>>> print("j'ai reçu", sf)
Structures de données simple
>>> a = 3
>>> type(a)
>>> print(a)
>>> b = a
✤ bool
>>> b = 5
✤ int
>>> b/9
✤ float >>> b//9
✤ string >>> b%9
>>> print(a)
>>> s = (b==a)
>>> t = False
>>> print(s and t)
>>> s != t
Float

>>> a = 1.1 ✤ Modèle pour les nombres réels


>>> 0.1 + 0.1 + 0.1 ✤ il s'agit de nombres flottants....
>>> b = float(3) ✤ Fonctions mathématiques
✤ Nombres aléatoires

>>> import math


>>> math.cos(0)
>>> math.acos(0)

>>> import random


>>> a = random.random()
>>> b = random.randint(1,3)
Random walk (marche aléatoire)
A chaque étape, avec probabilité 1/2, on ajoute/enlève 1.

Une étape:

Loi de Bernoulli avec p=1/2

n étapes:

Loi binomiale

Une réalisation avec n=10

>>> import random


>>> random.seed(10)
>>> b = random.randint(0,1)
>>> b = 2*b - 1
String
>>> a = "abc"
>>> b = 'abc'
✤ Accès >>> a==b
✤ Fonctions >>> len(a)

✤ len() >>> a.upper()


>>> c = a + b
✤ Méthodes
>>> d = 3*c
✤ lower()
>>> d[2]
✤ find('a') >>> d[-1]
✤ replace() >>> d[3:5]

✤ strip(' ') >>> d[::2]


>>> a, b, c = 'ab', 'ra', 'ca'
✤ join(['a', 'b'])
>>> d = '_'.join([a,b,c])

attention à la valeur de retour >>> d.split('_')


Indexation

>>> a = "abcdefghijklmnopqrstuvwxyz"
>>> # import string
>>> # a = string.ascii_lowercase
>>> a[-3]
>>> a[:-3]

'slice'
https://python.developpez.com/cours/apprendre-python-3/
Conditions
>>> a = 3
>>> #condition
>>> if a//2==0:
✤ If - elif - else >>> print("pair")
✤ While >>> else:
>>> print("impair")

>>> a = 10
>>> while a:
>>> print("a=",")
>>> a = a -1
>>> print("fin")
Boucles
>>> for i in range(10):
>>> print("i=", i)

>>> for i in range(20,100):


>>> prem = True
>>> for k in range(i): ✤ for
>>> if i//k == 0: ✤ while
>>> prem = False
✤ break/continue
>>> if prem:
>>> print("i=", i)
>>> break
...voir list plus tard
Help!
>>> import random
>>> dir(random)
✤ Messages d’erreur (!!!) >>> help(random)
✤ help() >>> # commentaire
✤ dir()
✤ Docstring

>>> a = 2
>>> # erreur de frappe
>>> print(aa)
Structure de données avancées

✤ def Fonctions

✤ list
✤ set Ensemble

✤ tuple (comme list, immutable)

✤ dict entrées

>>> def is_pair(a):


sorties >>> return a//2 ==0
>>> b = 12
>>> is_pair(12)
list [] tuple ()

✤ collection ordonnée >>> l = ['abra', 13]


✤ hétérogène >>> len(l)
✤ list : modifiable >>> l[0]
✤ tuple : non- >>> l[-1]
modifiable >>> l.append(l)
✤ Accès >>> l += [3,4]
✤ Fonctions >>> for e in l:
>>> print(e, type(e))
✤ Méthodes

>>> def toto(a):


>>> return (a//2, a%2)
>>> print(toto(11))
exemples list

>>> couleurs = ['trèfle', 'carreau', 'coeur', 'pique']


>>> if 'rouge' in couleurs:
>>> print("on ne parle pas de la même chose")
>>> for couleur in couleurs:
>>> print(couleur)
>>> couleurs.append("bleu")
>>> couleurs.extend(["kiwi","orange"])
>>> couleurs.remove("coeur")
>>> coul = couleurs.pop()
>>> l = [40, 31, 33, 64, 65, 47]
>>> m = max(l)
>>> l.index(m)
Random walk (2)

On peut maintenant créer une


liste de tous les incréments:
>>> inc = []
>>> n = 10
>>> for i in range(n):
>>> inc.append(2*random.randint(0,1)-1)
>>> print(inc)

Et calculer la position:

>>> pos = [0]


>>> for i in range(n):
>>> pos.append(pos[i]+inc[i]) ...et écrire une fonction pour
>>> print(pos) la création d'une marche
set

>>> l = 'abc'
✤ ensemble
>>> set(l)
✤ comme en mathématique >>> l[::-1]
✤ pas de doublons >>> s = set(l[::-1])
✤ pas d'ordre >>> s.union('a', 'z')
<latexit sha1_base64="R0Ago9uG8mdSFB8IC4HpyJ8ULXM=">AAAB/XicZY9LS8NAFIVv6qvWV9Slm2AVXJSQiI9uhKIblxXsA5pQJtPbduhMEjITsYTin1FwIW79F27Vf2OSuqjt2ZyPc+4MHC/kTCrL+tEKS8srq2vF9dLG5tb2jr6715RBHFFs0IAHUdsjEjnzsaGY4tgOIyTC49jyRjdZ33rASLLAv1fjEF1BBj7rM0pUGnX1a4djXzkJqRieE7HBUDkT48qYSSsGWSxm065etkwrl7EI9h+Ua0eQq97Vn51eQGOBvqKcSNmxrVC5CYkUoxwnJSeWGBI6IgPspOgTgdJN8q0T4zhMpxucGDSIOcbR7HVChJRj4VVSF0QNM1dDkRntzf2r+lU3YX4YK/Rp2uWYCEKjQJoKH7NZ9vyIRWiemvaFeX53Vq5Vp/ugCAdwCCdgwyXU4Bbq0AAKr/AJX/CtPWkv2pv2Pj0taH9v9uGftI9f4YuVsw==</latexit>

{a, b} = {a, b, a} = {b, a}


dict {}

>>> d = {}
>>> d['ana'] = '123'
✤ "dictionnaire"
>>> d['cléo'] = '173'
✤ tableaux associatifs >>> d.keys()
✤ comme une application >>> for k,v in d.items():
en mathématiques >>> print(k,"-->",v)

✤ clés - valeurs
<latexit sha1_base64="4M7iSyEYSpAMup6aNTrtAjIdGuc=">AAAB2nicZY/LSsNAFIZP6q3WW9SlC4PVUkFCIl6KIBTcuKxgL9KEMplO2tCZzJCZSEvoRnAhbn0Ed271YXwb07QLtf/m/2bOmYHPEzSQyrK+tdzC4tLySn61sLa+sbmlb+80JI8jTOqYUx61PCQJDUJSV4GipCUigphHSdMb3EzmzUcSyYCH92okiMtQLwz8ACOVXnX0ff+qZLQMR3HjwXEKpaHhMCRkehxd++XhcUcvWqaVxZgHewbF6iFkqXX0d6fLccxIqDBFUrZtSyg3QZEKMCXjghNLIhAeoB5ppxgiRqSbZCJj40ikXgZFBuYxJXH0eztBTMoR807SZkj1J636bFK4++9f5VfcJAhFrEiI01mGCUM44tJUZDhOtez/EvPQODXtC/P87qxYrUz9IA97cABlsOESqnALNagDhmf4gE/40hztSXvRXqerOW32Zhf+RHv7Adm9hnk=</latexit>

f :X ! Y
x 7! y = f (x)
Mots réservés

and, as, assert, break, class,


continue, def, del, elif, else,
except, False, finally, for, from,
global, if, import, in, is, lambda,
None, nonlocal, not, or, pass, raise,
return, True, try, with, while, and
yield.
P3 : Algorithmique

✤ Qu'est-ce que c'est une variable ?


✤ Quand et comment utiliser une condition
✤ Quand et comment utiliser une boucle
✤ Quelques algorithmes dans python
✤ Exemples : balayage, bisection, Monte-Carlo
Variables

>>> a = 3 variables memoire

>>> b = a a b 3

>>> b = b + 1 b
a 5 3

>>> b += 1 I

✤ Identificateur associé à une valeur


✤ En Python, c'est une référence d'objet.
✤ On affecte en utilisant le signe =
✤ L'introduction d'une variable est un choix
algorithmique
Conditions
>>> if x%2==0:
>>> y = f(x)
>>> elif x%3==0:
>>> y = g(x)
>>> else:
>>> print("ni divisible par 2 ni 3")

✤ Choisir >>> x = "abracadabra"

✤ Utilise un/plusieurs bool >>> found=False


>>> i=0
✤ Caché dans while >>> while(not found):
>>> if x[i]=="c:
>>> found = True
Boucles

✤ while
✤ for boucle sur une liste ou autre iterable
✤ Répétition d'instructions identiques :
itérations
✤ Pour des boucles complexes, on commence
par écrire une itération
Quelques algorithmes dans python

>>> a = [-2, 6, -9, 0, 7]


>>> print(max(a))
>>> print(sorted(a))
>>> def comp(a):
>>> return abs(a)
✤ sort >>> print(max(a, key = comp))

✤ max/min >>> print(sorted(a, key = comp))


Exemples

✤ Choix algorithmiques:
✤ Variables
✤ Fonctions
✤ Type de boucles
✤ Algorithme mathématique != informatique
y f(x)
=

Balayage : zéro d'une fonction


j 1 I 11 I 11I
>>> a, b, n = 1, 2, 100 c
si
m
b
h
pas
>>> h = (b-a)/(n-1) a ih,0cicn
ni
=
+

L'itération consiste à savoir si l'on est proche de la solution


h =
On essaye de trouver la plus petite borne supérieure/et la plus grande inférieure

>>> # on suppose d'avoir ppbs, x_ppbs et pgbi, x_pgbi et x


>>> if f(x)>=0:
>>> if f(x) <= ppbs:
>>> ppbs = f(x)
>>> x_ppbs = x
Il faut ensuite:
>>> else:
• augmenter x
>>> if f(x)>= pgbi:
• initialiser les variables
>>> pgbi = f(x)
• faire la boucle
>>> x_pgbi = x
Biscection : zéro d'une fonction y f(x)
=

ix ,,,
"
-changement
>>> a, b, niter = 1, 2, 100 c

b
X
de
signe!
L'itération consiste à diviser l'intervalle en comparant trois valeurs

>>> # on suppose d'avoir a,b


>>> m = 0.5*(a+b) Il faut ensuite:

>>> if f(a)*f(m)<=0: • initialiser: s'assurer que


f(a)f(b)<=0
>>> b = m
• faire la boucle
>>> else:
>>> a = m
C
=

Monte Carlo: calcul d'une intégrale y f(x)


=

-
110
b

1 Efface
IIII11194
>>> a, b, c, nsam = 1, 2, 2, 1000 -
->

>>> dx, dy = b-a, c-a /


*
c "
(n,y) [a; b) x [a;c] R
=

On tire au hasard (!?)


an hasard

p P((4,y) A)
=

=
>>> # on suppose d'avoir n_in =D1A1 p(R)
=

on estime p!
>>> from random import random
e (:(4+ 73
*
pe
>>> x,y = a+dx*random(), a+dy*random() M

>>> if f(x)<y:
>>> n_in += 1 Il faut ensuite:

• initialiser les variables

• faire la boucle
P4 : L’environnement

✤ Comment organiser un projet


✤ Modules standard
✤ Autres modules
Comment organiser un projet

✤ Éviter la duplication de code


✤ Fonctions
✤ Fichiers - Modules
Modules standard
>>> import math
✤ sys, os, >>> print(math.pi)
shutil, glob >>> from math import pi
✤ math, random >>> print(pi)

✤ matplotlib, >>> import numpy as np


numpy, scipy
✤ tkinter
✤ pandas
✤ sympy
✤ PIL
Autres Modules

✤ lecture de fichiers: Excel, SQL


✤ statistique, optimization, visualisation
✤ images, sons
P5 : Graphisme
https://matplotlib.org

✤ matplotlib.pyplot
✤ plusieurs plots
✤ histogrammes
✤ plots 3D
✤ animations
matplotlib.pyplot
>>> import matplotlib.pyplot as plt
>>> x, y = [0, 2, 4], [10,8,9]
>>> plt.plot(x,y)
>>> plt.show()

✤ plot() x-y >>> plt.ylabel('x')


✤ scatter() >>> plt.xlabel('t')
>>> plt.plot(x, y, label="f(x)")
✤ imshow()
>>> plt.legend()
✤ hist()
>>> plt.plot(x, y,'ro')
>>> plt.title('Titre')
>>> plt.grid()
Plusieurs plots

>>> plt.subplot(221)
>>> plt.plot(x, y1)
>>> plt.subplot(222)
>>> plt.yscale('log')
✤ plusieurs plots dans une axes
>>> plt.plot(x, y1)
✤ plusieurs plots dans différents axes >>> plt.subplot(223)
✤ axes (et fig) courant >>> plt.plot(x, y2)
>>> plt.subplot(224)
>>> plt.yscale('log')
>>> plt.plot(x, y2)
Random walk (3)
On peut maintenant montrer une m.a.:
>>> plt.plot(pos,'x-')
>>> plt.plot([0,n],[0,0], '--r')

Et utiliser un histogramme (voir exa) :

>>> plt.subplot(2,1,1)
>>> plt.plot(pos,'x-')
>>> plt.plot([0,n],[0,0], '--r')
>>> plt.subplot(2,1,2)
>>> p = [d[0] for d in sorted(hist.items())]
>>> h = [d[1] for d in sorted(hist.items())]
>>> plt.bar(p, h)
P6 : Langage avancé

✤ Fonctions
✤ Fichier
✤ Formattage
✤ Messages d’erreur
✤ Try - except
✤ Choses diverses
✤ Mutable - immutable
>>> def fct(arg):
Fonctions
>>> # faire qqchose
>>> return res
✤ plusieurs sorties
✤ plusieurs arguments >>> def fct(arg, n=10):

✤ arguments par default >>> ### docstring -> help


>>> explication, entrées, sorties
✤ key-word arguments
>>> ###
✤ fonctions récursives >>> # faire qqchose
✤ fonctions comme >>> return res
argument de fonctions
✤ fonctions lambda >>> fct() # erreur !
>>> fct("toto")
>>> fct(arg="toto")
>>> fct(arg="toto", n=100)
Fichiers
✤ ouvrir/fermer
✤ écrire/lire

>>> f = open("nom_fichier","w", encoding="utf8")


>>> f.write("toto\n")
>>> f.writelines(['liste', 'de', 'chaines','de', 'char'])
>>> f.close()

>>> f = open("nom_fichier","r", encoding="utf8")


>>> s = f.read() #tout le fichier
>>> s = f.readlines() #donne liste des lignes
>>> f.close()
Formattage

>>> a = math.pi
>>> print("pi={}".format(a))
>>> print("pi={:6.3f}".format(a))
✤ format()
>>> print("pi={:11.5e}".format(a))
✤ C-style >>> s = "chaine_de_charactères"

✤ f-string >>> print("{:30}".format(s))


>>> print("{:>30}".format(s))
✤ f"{a=}"
>>> print("{:.<30}".format(s))
>>> print("{:-^30}".format(s))
Messages d’erreur
>>> d = {'a':2, 'z':3 'f':7} >>> raise ValueError("??")

✤ SyntaxError >>> list_of_numbers = [1, 2, 3, 4, 5]


✤ NameError >>> list_of_numburs.remove(5)
✤ ValueError
>>> math.sin("???")
✤ IndexError
✤ KeyError >>> math.log(-1) >>> l = [1,2]

✤ TypeError >>> l[2]


>>> d = {1:"a",2:"b"}
✤ AttributeError >>> d[0]
✤ IndentationError
>>> import math >>> for i in range(3):
>>> math.pii >>> i2 = i**2
Try - except ✤ Éviter des tests
✤ Traiter des erreurs

>>> try:
>>> f = open('myfile.txt')

>>> s = f.readline()

>>> i = int(s.strip())

>>> except OSError as err:


>>> print("OS error:", err)

>>> except ValueError:


>>> print("Could not convert data to an integer.")

>>> except Exception as err:


>>> print(f"Unexpected {err=}, {type(err)=}")

>>> raise
Choses diverses
>>> l = [i**2 for i in range(10)]
>>> d = {i:i**2 for i in range(10)}

>>> with open("test.txt", "w") as f :


>>> f.write(chain)

>>> a, b, c = 2, 4, 'abra'

>>> plus_petit = x if x < y else y


✤ list comprehension
✤ ouverture de fichiers avec with
✤ utilisation des tuple
✤ boucles avec enumerate >>> for i,l in enumerate(ls):
>>> print(i, l)
Mutable - immutable
>>> x = 3
>>> y = x
>>> print(x, y, id(x), id(y))
>>> y = 6
>>> print(x, y, id(x), id(y))
>>> x = ['a', 'b', 'c']
>>> y = x
>>> print(x, y, id(x), id(y))
>>> y[0] = 'y'
>>> print(x, y, id(x), id(y))
P7 : Algèbre linéaire

✤ numpy : ndarray
https://numpy.org
✤ numpy : linalg

Fonctions/méthodes pour l'algèbre linéaire


Un type données n-dimensional-array
• 0-dimensional : scalaires : 0 indices
• 1-dimensional : vecteurs : 1 indice
• 2-dimensional : matrices : 2 indices
• pourquoi pas plus ?
>>> import numpy as np
Accès efficace, fonctions sectorisées
ndarray
✤ Structure
✤ homogène
✤ tensoriel
✤ Création
✤ lecture fichier/web
✤ copies
✤ fonctions
>>> a = np.array([2,6,4])
✤ Manipulations >>> a.shape
✤ formes >>> a = np.array([[2,6],[3,1]])
>>> a.ndim # = len(a.shape)
✤ fonctions
Création >>> a = np.arange(6)
>>> a = np.linspace(1,3)
>>> a = np.array([2,6])
>>> a = np.empty(3) >>> a = np.random.rand(3)
>>> b = np.empty_like(a) >>> a = np.random.randn(2,2)
>>> a = np.zeros(3)
>>> b = np.zeros_like(a)
>>> a = np.loadtxt(fname)

>>> a = 3*np.ones(5)
>>> np.save("filename",a)
>>> c = a.copy()
>>> a = np.load("filename")

>>> import requests, io


>>> url ='https://my_url/my_np_file.npy'
>>> response = requests.get(url)
>>> response.raise_for_status()
>>> data = np.load(io.BytesIO(response.content))
>>> a = np.arange(9) Manipulations
>>> b = a.reshape(3,3)
>>> c = b.T
>>> print(a.shape, b.shape)
>>> print(b, c)
>>> print(b[2,1], c[2,1])
>>> a = np.arange(9)
>>> b = a[::-1]
>>> a+1
>>> 2**a
>>> np.sin(a)
>>> a*b
>>> c = np.arange(4).reshape(2,2)
>>> d = c*c
>>> e = np.dot(c,c)
>>> print(c, 2*'\n', d, 2*'\n', e)
Fancy indexing

>>> a = 10*np.random.rand(12)
>>> a[a>5] = -1

>>> i = a>5 # opération bool


>>> a[i] # fancy index
Quelques utilisations

>>> import numpy as np


>>> import matplotlib.pyplot as plt
>>> d = np.linspace(0, 365, 365)
>>> t = 12 + 1.5*np.random.randn(365) + 10*np.sin(d*np.pi/364)
>>> plt.plot(d, t)
>>> plt.show()

>>> i = np.where(t>20)
>>> minval = np.min(t)*np.ones_like(i)
>>> plt.plot(i, minvals, 'rx')
Random walk (4)
C'est plus rapide et simple avec numpy

>>> # random seed


>>> rng = np.random.default_rng(11111)
>>> n = 10000
>>> inc = 2*rng.integers(0,2, size=n)-1
>>> pos = np.zeros(n+1)
>>> pos[1:] = np.cumsum(inc)
>>> plt.subplot(2,1,1)
>>> plt.plot(pos,'x-')
>>> nb = int(pos.max()-pos.min())
>>> h, bins = np.histogram(pos, bins = nb)
>>> plt.subplot(2,1,2)
>>> plt.bar(bins[:-1],h)
np.linalg
✤ Opérations sur les vecteurs
<latexit sha1_base64="w9SeMqd6FiHFdMNXnitO+bgeyN8=">AAABxHicZY/JTsJQFIZPcUKcUJduGtHEhWla4sCSxMS4RCNDApXcXg5wwx2a3lsjafAt3OrGl/JtbAsLhX/zfzlTzh+EnGnjuj9WYW19Y3OruF3a2d3bPygfHrW0iiOKTaq4ijoB0ciZxKZhhmMnjJCIgGM7mNxl/fYrRpop+WymIfqCjCQbMkpMWur2BDHjILCfXmS/XHEdN5e9Ct4CKvUzyNXol797A0VjgdJQTrTuem5o/IREhlGOs1Iv1hgSOiEj7KYoiUDtJ/nLM/s8TBPYnNhUxRzj6O90QoTWUxFcpp79l7kZi8zoYOmuGdb8hMkwNihp2ssxEYRGSjsG32ZpLG85xCq0qo5341w/XlXqtXk+KMIJnMIFeHALdXiABjSBgoIP+IQv697ilrbi+WjBWuwcwz9Z77+zLH/9</latexit>

n
✤ espace vectoriel euclidien R
✤ addition

✤ multiplication scalaire

✤ produit scalaire

✤ autres fonctions
✤ min, max, argmin, argmax, mean, var, diff, sum, cumsum, sort

✤ Opérations sur les matrices <latexit sha1_base64="Vnt+lpqDQVNIy/ZDOqfmvftHIU4=">AAAB0HicZY/LTsJAFIZP8YZ4qxpXbhrRxIUhrfHCksSNSyRySWgl0+EAE2amTWdqIA0xbn0LE1f6RL6NbWWh8G/+L+cyc34/5Exp2/42Ciura+sbxc3S1vbO7p65f9BSQRxRbNKAB1HHJwo5k9jUTHPshBES4XNs++O7rN9+xkixQD7qaYieIEPJBowSnZZ65pEriB75vtV4SoSrmUBlyVnPLNsVO5e1DM4cyrVTyFXvmR9uP6CxQKkpJ0p1HTvUXkIizSjHWcmNFYaEjskQuylKkv7jJfn5M+ssTNNYnFg0iDnG0d/phAilpsK/SD27NHM9EpnR/sK7elD1EibDWKOkaS/HRBAaBaqicZLFchZDLEPrsuLcVK4frsq16m8+KMIxnMA5OHALNbiHOjSBQgLv8AlfRsOYGC/G6+9owZjvHMI/GW8/LaaElQ==</latexit>

m⇥n
✤ mêmes que les vecteurs ! R
✤ multiplication matrice-matrice, matrice-vecteur
✤ calcul valeurs/vecteurs propres, determinants, inversion,..
Création matrices

>>> a = np.eye(3)
>>> a = a + 1
>>> print(a)
✤ fonctions par ndim=2 >>> b = np.arange(9)
✤ extraction lignes/ >>> b = b.reshape(3,3)
colonnes >>> print(b)
>>> print(b[2])
>>> print(b[2,:])
>>> print(b[:,1])
np.linalg

✤ np ou np.linalg >>> import numpy as np

✤ multiplications >>> a = np.random.rand(3)


>>> b = np.arange(3)
✤ transposée
>>> np.dot(a,b)
✤ algorithmes (!) >>> a.dot(b)
✤ valeurs/vecteurs propres >>> A = np.linspace(1,2,9)
✤ décompositions >>> A = A.reshape(3,3)

✤ solution d'équations >>> np.dot(A,b)


linéaires (systèmes) >>> A[2,:] += 2*np.diag(A)
>>> A -= 2*A.T
>>> np.linalg.eigvals(A)
>>> np.linalg.eig(A)

Vous aimerez peut-être aussi