Vous êtes sur la page 1sur 10

Les Bibliothèques mathématiques

Le module numpy
La bibliothèque NumPy (http://www.numpy.org/) permet d’effectuer des calculs numériques avec
Python. Elle introduit une gestion facilitée des tableaux de nombres.

Il faut au départ importer le package numpy avec l’instruction suivante :

In [2]: import numpy

On utilise as pour simplifier le nom lors de l'utilisation

In [3]: import numpy as np

Fonctions mathématiques avec NumPy


nombre aléatoire entre 0 et 1
In [4]: a = np.random.random()
print(a)

0.6198238392789901

Arrondissement
In [5]: x = 3.2598
np.around(x,2)

3.26
Out[5]:

Tableaux - numpy.array()
Les tableaux (en anglais, array) peuvent être créés avec numpy.array(). On utilise des crochets pour
délimiter les listes d’éléments dans les tableaux.

Les Tableaux numpy ont plusieurs fonctionalitées additionnelles.

In [6]: a = np.array([1, 2, 3, 4])

In [7]: a = [1, 2, 3, 4]
print(type(a))

<class 'list'>

In [8]: a = np.array([1, 2, 3, 4])


print(type(a))
<class 'numpy.ndarray'>

Accès aux éléments d’un tableau


In [9]: a = np.array([1, 2, 3, 4])
print(a[1])

In [10]: a[i][j]

a[i,j]

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
C:\Users\REVMIR~1\AppData\Local\Temp/ipykernel_8328/1103745718.py in <module>
----> 1 a[i][j]
2
3 a[i,j]

NameError: name 'i' is not defined

In [11]: a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])


print(a[1, 2])
print(a[0, 1])
print(a[2, 0])

6
2
7

La forme d'un tableau


In [12]: a = np.array([1, 2, 3])
print(a.shape)

b = np.array([[1,2,3],[4,5,6],[9,8]])
print(b.shape)

(3,)
(3,)
C:\Users\REVMIR~1\AppData\Local\Temp/ipykernel_8328/2688639039.py:4: VisibleDeprecationWarn
ing: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or
-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do thi
s, you must specify 'dtype=object' when creating the ndarray.
b = np.array([[1,2,3],[4,5,6],[9,8]])

Le nombre d'elements - size()


In [19]: a = np.array([1, 2, 3])
print(np.size(a))

b = np.array([[1,2,3],[4,5,6]])
print(np.size(b))

3
6
Créé un tableau
In [20]: a = np.zeros((2,2)) # Create an array of all zeros
print(a)

[[0. 0.]
[0. 0.]]

In [22]: b = np.ones((3,2)) # Create an array of all ones


print(b)

[[1. 1.]
[1. 1.]
[1. 1.]]

In [ ]: b + 5

multiplication et addition
In [23]: b = np.ones((3,3))
c = b*9
print(c)

[[9. 9. 9.]
[9. 9. 9.]
[9. 9. 9.]]

In [24]: b = np.ones((3,3))
c = b+9
print(c)

[[10. 10. 10.]


[10. 10. 10.]
[10. 10. 10.]]

Tableaux et slicing
In [26]: a = np.array([12, 25, 34, 56, 87])
print(a[1:3])

[25 34]

In [27]: a = np.array([[1, 2, 3], [4, 5, 6]])

In [28]: print(a[0,1])

2
Out[28]:

In [30]: print(a[:,1:3])

[[2 3]
[5 6]]

In [31]: print(a[0,:])

[1 2 3]

In [32]: print(a[:,1])
[2 5]

In [ ]:

Subdivision d'un intervalle


np.linspace(a, b, n) retourne une liste avec des elements entre a et b, le nombre d'elements est n.

In [37]: L = np.linspace(0, 10, 5)


print(L)

[ 0. 2.5 5. 7.5 10. ]

In [15]: L = np.linspace(0, 1, 10)


print(L)

[0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556


0.66666667 0.77777778 0.88888889 1. ]

In [ ]:

In [ ]:

Tracé de courbes : Le module matplotlib


Pour tracer des courbes, Python n’est pas suffisant et nous avons besoin de la bibliothèque Matplotlib

In [18]: import numpy as np


import matplotlib.pyplot as plt

In [24]: def x_carre(x):


return x**2

In [26]: X = np.linspace(-2, 2, 100)


Y = x_carre(X)

plt.plot(X,Y)
plt.show()

In [29]: plt.plot([1,1,2,2,1],[1,2,2,1,1])
plt.show()
Création d’une courbe - plot()
La fonction plt.plot() prend 2 liste qui represente des points, une liste des abscisses et une liste des
ordonnée. le fonction plt.plot() trace des lien entre chaques deux points successive.

In [31]: import numpy as np


import matplotlib.pyplot as plt

In [32]: plt.plot([1, 3, 4, 6], [2, 3, 5, 1])


plt.show() # affiche la figure à l'écran

In [33]: a = 0
b = 2*np.pi
n = 30
x = np.linspace(a, b, n)
y = []
for i in range(n):
y.append(np.cos(x[i]))

plt.plot(x, y)
plt.show() # affiche la figure à l'écran
In [34]: print(type(x))

<class 'numpy.ndarray'>

In [35]: x = np.linspace(a, b, n)
y = np.exp(x)
plt.plot(x, y)
plt.show() # affiche la figure à l'écran

In [36]: def f1(x):


return x**2 - 1

In [37]: a = -5
b = 5
n = 3

x = np.linspace(a, b, n)
y = f1(x)

plt.plot(x, y)
plt.show() # affiche la figure à l'écran
In [38]: a = -5
b = 5
n = 20

x = np.linspace(a, b, n)
y1 = f1(x)
y2 = np.sin(x)

plt.plot(x, y1, label="f1")


plt.plot(x, y2, label="sin")

plt.title("Fonction cosinus")
plt.legend()

plt.show() # affiche la figure à l'écran

In [41]: a = -5
b = 5
n = 200

x = np.linspace(a, b, n)
y1 = f1(x)
y2 = np.sin(x)

plt.plot(x, y1, label="f1")


plt.plot(x, y2, label="sin")

plt.title("Fonction cosinus")
plt.xlim((-2,2)) #limiter la vue de la figure
plt.ylim((-2,2)) #limiter la vue de la figure
plt.legend()

plt.show() # affiche la figure à l'écran

In [45]: a = -10
b = 10
n = 200

x1 = np.linspace(a, 0, n//2)
y1 = 1/x1
x2 = np.linspace(0, b, n//2)
y2 = 1/x2

plt.plot(x1, y1)
plt.plot(x2, y2)

plt.title("Fonction cosinus")

plt.show() # affiche la figure à l'écran

C:\Users\REVMIR~1\AppData\Local\Temp/ipykernel_8328/1698584929.py:6: RuntimeWarning: divide


by zero encountered in true_divide
y1 = 1/x1
C:\Users\REVMIR~1\AppData\Local\Temp/ipykernel_8328/1698584929.py:8: RuntimeWarning: divide
by zero encountered in true_divide
y2 = 1/x2
In [ ]:

Vous aimerez peut-être aussi