SymPy

La bibliothèque SymPy est spécialisée dans le calcul symbolique. Elle ne dépend d’aucune bibliothèque supplémentaire. Elle permet de faire

  • arithmétique

  • algèbre

  • calcul matriciel

  • résolution d’équations

Source

Tout d’abord nous importons toutes les méthodes (*) depuis le module sympy.

from sympy import *

Exercice
Si vous rencontrez une erreur ModuleNotFoundError vous devez d’abord installer le module sympy.

Calcul symbolique ?

C’est quoi le calcul symbolique?

La fonction sqrt du module math permet de calculer une racine carrée. Le nombre affiché n’est pas la valeur exacte. La racine de 2 ne peux pas être représenté par un nombre à virgule flottante.

import math
math.sqrt(2)
1.4142135623730951

Si nous faisons l’opération inverses, le carré, il reste une petite erreur.

2 - math.sqrt(2) ** 2
-4.440892098500626e-16

Par contre si nous utilisons la fonction sqrt que nous venons d’importer du module sympy nous gardons une expression symbolique pour la racine.

sqrt(2)
\[\displaystyle \sqrt{2}\]

Si nous faisons l’opération inverse, il n’y a pas d’erreur d’arrondi.

2 - sqrt(2) ** 2
\[\displaystyle 0\]

En plus, le calcul symbolique peut être simplifié.

sqrt(8)
\[\displaystyle 2 \sqrt{2}\]

Un exemple plus intéressant.

Nous définissons deux symboles

x, y = symbols('x y')
expr = x + 2*y
expr
\[\displaystyle x + 2 y\]

Voici une fonction composée.

f = sin(x)*exp(x)
f
\[\displaystyle e^{x} \sin{\left(x \right)}\]

Nous pouvons la différencier par rapport à x.

diff(f, x)
\[\displaystyle e^{x} \sin{\left(x \right)} + e^{x} \cos{\left(x \right)}\]

Développement

Définissons les symboles a et b et formons une expression.

a, b = symbols('a b')
e = (a + b)**5
e
\[\displaystyle \left(a + b\right)^{5}\]

La méthode expand permet de développer l’expression.

e.expand()
\[\displaystyle a^{5} + 5 a^{4} b + 10 a^{3} b^{2} + 10 a^{2} b^{3} + 5 a b^{4} + b^{5}\]

La méthode factor permet de la factoriser.

_.factor()
\[\displaystyle \left(a + b\right)^{5}\]

Dérivée

Définissons deux variables x et y et formons une fonction f.

x, y = symbols('x, y')
f = x**2 / y + 2 * x - ln(y)
f
\[\displaystyle \frac{x^{2}}{y} + 2 x - \log{\left(y \right)}\]

Nous pouvons différencier la fonction par rapport à x.

diff(f, x)
\[\displaystyle \frac{2 x}{y} + 2\]

Et une deuxième fois par rapport à y.

diff((diff(f, x)), y)
\[\displaystyle - \frac{2 x}{y^{2}}\]

Intégrale

Nous pouvons calculer une intégrale.

a = Integral(cos(x)*exp(x), x)
Eq(a, a.doit())
\[\displaystyle \int e^{x} \cos{\left(x \right)}\, dx = \frac{e^{x} \sin{\left(x \right)}}{2} + \frac{e^{x} \cos{\left(x \right)}}{2}\]

Expansion, factorisation

Nous définissons une expression simple.

x, y = symbols('x, y')
expr = x + 2*y
expr
\[\displaystyle x + 2 y\]

Nous poumvons soustraire un terme.

expr - x

Nous pouvons multplier par un terme.

x*expr
\[\displaystyle x \left(x + 2 y\right)\]

Nous pouvons développer le résultat.

expand(x*expr)
\[\displaystyle x^{2} + 2 x y\]

Nous pouvons factoriser une expression.

factor(x**2-y**2)
\[\displaystyle \left(x - y\right) \left(x + y\right)\]

Nous pouvons différencier une expression.

x, t, z, nu = symbols('x t z nu')
diff(sin(x)*exp(x), x)
\[\displaystyle e^{x} \sin{\left(x \right)} + e^{x} \cos{\left(x \right)}\]

Et nous pouvons l’intégrer de nouveau.

integrate(_, x)
\[\displaystyle e^{x} \sin{\left(x \right)}\]

Nous pouvons intégrer sur une intervalle infinie.

integrate(sin(x**2), (x, -oo, oo))
\[\displaystyle \frac{\sqrt{2} \sqrt{\pi}}{2}\]

Calculer une limite.

limit(sin(x)/x, x, 0)
\[\displaystyle 1\]

Résoudre une écuation quadratique

solve(x**2 - 3*x - 2, x)
[3/2 - sqrt(17)/2, 3/2 + sqrt(17)/2]
y = Function('y')
dsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t))
\[\displaystyle y{\left(t \right)} = C_{2} e^{- t} + \left(C_{1} + \frac{t}{2}\right) e^{t}\]

Définir une matrice.

M = Matrix([[1, 2], [2, 2]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2\\2 & 2\end{matrix}\right]\end{split}\]

Calculer sa valeur propre.

M.eigenvals()
{3/2 - sqrt(17)/2: 1, 3/2 + sqrt(17)/2: 1}

Simplification

Les méthodes simplify, factor et expand permettent de transformer des expressions.

e = sin(x)**2 + cos(x)**2
e
\[\displaystyle \sin^{2}{\left(x \right)} + \cos^{2}{\left(x \right)}\]
e.simplify()
\[\displaystyle 1\]
e2 = x**2 + 2*x + 1
e2
\[\displaystyle x^{2} + 2 x + 1\]
e2.factor()
\[\displaystyle \left(x + 1\right)^{2}\]
e5 = (x-1)**5
e5
\[\displaystyle \left(x - 1\right)^{5}\]
e5.expand()
\[\displaystyle x^{5} - 5 x^{4} + 10 x^{3} - 10 x^{2} + 5 x - 1\]
factor(x**5 + x**4 + x**3 + x**2 + x + 1)
\[\displaystyle \left(x + 1\right) \left(x^{2} - x + 1\right) \left(x^{2} + x + 1\right)\]

Matrices

Pour créer une matrice en SymPy utilisez le constructeur Matrix() et en donnant une liste des vecteurs-ligne comme argument.

M = Matrix([[1, -1], [3, 4], [0, 2]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & -1\\3 & 4\\0 & 2\end{matrix}\right]\end{split}\]

Pour créer une matrice-colonne, une liste simple d’éléments est suffisant.

Matrix([1, 2, 3])
\[\begin{split}\displaystyle \left[\begin{matrix}1\\2\\3\end{matrix}\right]\end{split}\]

Pour créer une matrice-ligne, une double-liste d’éléments est nécessaire.

Matrix([[1, 2, 3]])
\[\displaystyle \left[\begin{matrix}1 & 2 & 3\end{matrix}\right]\]

Matrices peuvet être multipliées avec l’opérateur *.

M = Matrix([[1, 2, 3], [3, 2, 1]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2 & 3\\3 & 2 & 1\end{matrix}\right]\end{split}\]
N = Matrix([0, 1, 1])
N
\[\begin{split}\displaystyle \left[\begin{matrix}0\\1\\1\end{matrix}\right]\end{split}\]

Voici le produit matriciel de deux matrices.

M*N
\[\begin{split}\displaystyle \left[\begin{matrix}5\\3\end{matrix}\right]\end{split}\]

Voici le produit avec un scalaire.

k = Symbol('k')
M*k
\[\begin{split}\displaystyle \left[\begin{matrix}k & 2 k & 3 k\\3 k & 2 k & k\end{matrix}\right]\end{split}\]

Contrairement aux autres objets dans SymPy, les matrice sont mutables. Donc elles peuvent être modifiés en place.

Opérations de base

Considérons la matrice

M = Matrix([[1, 2, 3], [-2, 0, 4]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2 & 3\\-2 & 0 & 4\end{matrix}\right]\end{split}\]

La méthode shape retourne le nombre de lignes et colonnes \((n, m)\)

M.shape
(2, 3)

La méthode len retourne le nombre total de coéfficients (\(n \times m\))

len(M)
6

On peut accéder à un élément de la matrice par son indices.

M[5]
\[\displaystyle 4\]

Itérer avec l’instruction for sur une matrice accède à tout ses éléments, lignes par ligne.

for m in M:
    print(m, end='  ')
1  2  3  -2  0  4  

Accéder aux lignes et colonnes

La méthode row permet d’extraire une ligne.

M.row(0)
\[\displaystyle \left[\begin{matrix}1 & 2 & 3\end{matrix}\right]\]

La méthode col permet d’extraire une colonne.

M.col(0)
\[\begin{split}\displaystyle \left[\begin{matrix}1\\-2\end{matrix}\right]\end{split}\]

La méthode col_delpermet de supprimer une colonne.

M.col_del(0)
M
\[\begin{split}\displaystyle \left[\begin{matrix}2 & 3\\0 & 4\end{matrix}\right]\end{split}\]

La méthode row_del permet de supprimer une ligne. Cette opération modifie la matrice en place et retourne None.

M.row_del(1)
M
\[\displaystyle \left[\begin{matrix}2 & 3\end{matrix}\right]\]

Les méthodes row_insert et col_insert insèrent une ligne ou une colonne, mais pas en pace. Elle retournent une nouvelle matrice.

M.row_insert(1, Matrix([[0, 4]]))
\[\begin{split}\displaystyle \left[\begin{matrix}2 & 3\\0 & 4\end{matrix}\right]\end{split}\]

Vérfions que la matrice \(M\) n’a pas changé.

M
\[\displaystyle \left[\begin{matrix}2 & 3\end{matrix}\right]\]

Pour changer la matrice, nous devons affecter l’opération à son symbole.

M = M.row_insert(1, Matrix([[0, 4]]))
M
\[\begin{split}\displaystyle \left[\begin{matrix}2 & 3\\0 & 4\end{matrix}\right]\end{split}\]

Opérations de base

Soient deux matrices \(M\) et \(N\) de taille \(2 \times 2\).

M = Matrix([[1, 3], [-2, 3]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 3\\-2 & 3\end{matrix}\right]\end{split}\]
N = Matrix([[0, 3], [0, 7]])
N
\[\begin{split}\displaystyle \left[\begin{matrix}0 & 3\\0 & 7\end{matrix}\right]\end{split}\]

Voici l”addition

M+N
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 6\\-2 & 10\end{matrix}\right]\end{split}\]

Voici la soustraction

M-N
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0\\-2 & -4\end{matrix}\right]\end{split}\]

Voici la multiplication

M*N
\[\begin{split}\displaystyle \left[\begin{matrix}0 & 24\\0 & 15\end{matrix}\right]\end{split}\]

Voici la puissance 2

M**2
\[\begin{split}\displaystyle \left[\begin{matrix}-5 & 12\\-8 & 3\end{matrix}\right]\end{split}\]

La puissance -1 donne l”inverse d’une matrice.

M**(-1)
\[\begin{split}\displaystyle \left[\begin{matrix}\frac{1}{3} & - \frac{1}{3}\\\frac{2}{9} & \frac{1}{9}\end{matrix}\right]\end{split}\]

La transposé

La méthode T retourne la transposé d’une matrice.

M = Matrix([[1, 2, 3], [4, 5, 6]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2 & 3\\4 & 5 & 6\end{matrix}\right]\end{split}\]
M.T
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 4\\2 & 5\\3 & 6\end{matrix}\right]\end{split}\]

Matrice particuliers

La fonction eye(n) retourne une matrice d’identité.

eye(3)
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]\end{split}\]

La fonction zeros(n, m) retourne une matrice zéro.

zeros(3, 5)
\[\begin{split}\displaystyle \left[\begin{matrix}0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0\end{matrix}\right]\end{split}\]

La fonction ones(n, m) retourne une matrice dont tous les éléments valent 1.

ones(2, 4)
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 1 & 1 & 1\\1 & 1 & 1 & 1\end{matrix}\right]\end{split}\]

La fonction diag retourne une matrice diagonale.

diag(1, 2, 3)
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 2 & 0\\0 & 0 & 3\end{matrix}\right]\end{split}\]

Tous ces méthodes fonction aussi avec des symboles.

x, y, z = symbols('x y z')
diag(x, y, z)
\[\begin{split}\displaystyle \left[\begin{matrix}x & 0 & 0\\0 & y & 0\\0 & 0 & z\end{matrix}\right]\end{split}\]

Déterminant

La méthode det() calcule le déterminant d’une matrice.

M = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0 & 1\\2 & -1 & 3\\4 & 3 & 2\end{matrix}\right]\end{split}\]
M.det()
\[\displaystyle -1\]

Dans le cas d’une matrice \(2 \times 2\) le déterminant est:

a, b, c, d = symbols('a b c d')
M = Matrix([[a, b], [c, d]])
M.det()
\[\displaystyle a d - b c\]

Le déterminant d’une matrice identié est

eye(3).det()
\[\displaystyle 1\]
M.nullspace()
[]
A = Matrix([[1, 2], [-1, 3]])
A
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2\\-1 & 3\end{matrix}\right]\end{split}\]
A.eigenvals()
{2 - I: 1, 2 + I: 1}
A.eigenvects()
[(2 - I,
  1,
  [Matrix([
   [1 + I],
   [    1]])]),
 (2 + I,
  1,
  [Matrix([
   [1 - I],
   [    1]])])]

Equations

Eq(x, y)
\[\displaystyle x = y\]
eq = Eq(x**2 + 2*x + 1, 0)
eq
\[\displaystyle x^{2} + 2 x + 1 = 0\]
solveset(eq, x)
\[\displaystyle \left\{-1\right\}\]
linsolve([x + y + z -1, x + y + 2*z - 3], (x, y, z))
\[\displaystyle \left\{\left( - y - 1, \ y, \ 2\right)\right\}\]
Eq(x + y + z -1, x + y + 2*z - 3)
\[\displaystyle x + y + z - 1 = x + y + 2 z - 3\]
diag(1, 2) * M
\[\begin{split}\displaystyle \left[\begin{matrix}a & b\\2 c & 2 d\end{matrix}\right]\end{split}\]
N
\[\begin{split}\displaystyle \left[\begin{matrix}0 & 3\\0 & 7\end{matrix}\right]\end{split}\]

Permutation de lignes et colonnes

M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
M
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 2 & 3\\4 & 5 & 6\\7 & 8 & 9\end{matrix}\right]\end{split}\]

Une matrice anti-diagonale permet de basculer une matrice.

A = Matrix([[0, 0, 1], [0, 1, 0], [1, 0, 0]])
A
\[\begin{split}\displaystyle \left[\begin{matrix}0 & 0 & 1\\0 & 1 & 0\\1 & 0 & 0\end{matrix}\right]\end{split}\]

Permutation des colonnes de \((2, 1, 0)\)

M * A
\[\begin{split}\displaystyle \left[\begin{matrix}3 & 2 & 1\\6 & 5 & 4\\9 & 8 & 7\end{matrix}\right]\end{split}\]

Permutation des lignes de (2, 1, 0)

A * M
\[\begin{split}\displaystyle \left[\begin{matrix}7 & 8 & 9\\4 & 5 & 6\\1 & 2 & 3\end{matrix}\right]\end{split}\]

Horizontalement et verticalement

A * M * A
\[\begin{split}\displaystyle \left[\begin{matrix}9 & 8 & 7\\6 & 5 & 4\\3 & 2 & 1\end{matrix}\right]\end{split}\]
B = Matrix([[0, 1, 0], [0, 0, 1], [1, 0, 0]])
B
\[\begin{split}\displaystyle \left[\begin{matrix}0 & 1 & 0\\0 & 0 & 1\\1 & 0 & 0\end{matrix}\right]\end{split}\]

Les colonnes sont permuté de \((2, 0, 1)\)

M * B
\[\begin{split}\displaystyle \left[\begin{matrix}3 & 1 & 2\\6 & 4 & 5\\9 & 7 & 8\end{matrix}\right]\end{split}\]

Les lignes sont permuté de \((1, 2, 0)\)

B * M
\[\begin{split}\displaystyle \left[\begin{matrix}4 & 5 & 6\\7 & 8 & 9\\1 & 2 & 3\end{matrix}\right]\end{split}\]
C = Matrix([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
C
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 0 & 1\\0 & 1 & 0\end{matrix}\right]\end{split}\]

Permutation des colonnes \((0, 2, 1)\)

M * C
\[\begin{split}\displaystyle \left[\begin{matrix}1 & 3 & 2\\4 & 6 & 5\\7 & 9 & 8\end{matrix}\right]\end{split}\]