diff --git a/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.3-4. Notation Matricielle-checkpoint.ipynb b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.3-4. Notation Matricielle-checkpoint.ipynb index 5ec47b1..ecb6cf6 100644 --- a/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.3-4. Notation Matricielle-checkpoint.ipynb +++ b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.3-4. Notation Matricielle-checkpoint.ipynb @@ -1,530 +1,563 @@ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Concept(s)-clé(s) et théorie\n", "\n", "On considère un système d'équations linéaires aux inconnues $x_1,\\ldots,x_n$\n", "\n", "$$S=\\left\\{\\begin{array}{ccccccc}\n", "a_{11}x_1 &+a_{12}x_2 & + &\\cdots &+a_{1n}x_n &= &b_1 \\\\\n", "a_{21}x_1 &+a_{22}x_2 & + &\\cdots &+a_{2n}x_n &= &b_2 \\\\\n", "\\vdots & & & &\\vdots & \\vdots &\\vdots \\\\\n", "a_{m1}x_1 &+a_{m2}x_2 & + &\\cdots &+a_{mn}x_n &= &b_m\n", "\\end{array},\\right. $$\n", "\n", "où $a_{ij},b_i\\in \\mathbb{R}$ pour tout $1\\leq i\\leq m$ et tout $1\\leq j\\leq n.$ \n", "\n", "Le système $S$ peut s'écrire sous forme matricielle $A\\overrightarrow{x}=\\overrightarrow{b}$ où la matrice $A$ est appelée *la matrice des coefficients* et $\\overrightarrow{x}$ et $\\overrightarrow{b}$ sont des vecteurs contant les composantes $x_i$ et $b_i$ respectivement. \n", "\n", "Plus précisemment\n", "$$A=\\begin{pmatrix}\n", "a_{11} & a_{12} & \\cdots & a_{1n}\\\\\n", "a_{21} & a_{22} &\\cdots & a_{2n}\\\\\n", "\\vdots & \\vdots & \\ddots & \\vdots\\\\\n", "a_{m1} & a_{m2} & \\cdots & a_{mn}\n", "\\end{pmatrix},\\hskip1em\n", "\\overrightarrow{x}=\\begin{pmatrix}\n", "x_1\\\\\n", "x_2\\\\\n", "\\vdots\\\\\n", "x_n\n", "\\end{pmatrix},\\hskip1em\n", "\\overrightarrow{b}=\n", "\\begin{pmatrix}\n", "b_1\\\\\n", "b_2\\\\\n", "\\vdots\\\\\n", "b_m\n", "\\end{pmatrix},\n", "$$\n", "\n", "---\n", "\n", "La matrice $A$ est de taille $m\\times n$ où **m correspond au nombre de lignes** et **n au nombre de colonnes**.\n", "Le vecteur $\\overrightarrow{x}$ est de taille $n\\times 1$ et le vecteur $\\overrightarrow{b}$ de taille $m\\times 1$.\n", "\n" ] }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 1, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/html": [ + " \n", + " " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "import AL_Fct as al\n", "import numpy as np\n", "import ipywidgets as widgets\n", "import random\n", "\n", "from ipywidgets import interact, interactive, fixed, interact_manual" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **EXERCICE 1**\n", "\n", "Ci-dessous est générée une matrice $A$ de taille $m\\times n$. Trouver la dimension de la matrice en remplissant les deux champs dans lesquels vous pouvez rentrer une valeur pour $m$ et $n$. \n", "\n", "Vérifier en cliquant sur **Run Interact**" ] }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/latex": [ - "$\\left(\\begin{array}{ccccc} 63 & -78 & -14 & -77 & 73 \\\\54 & 5 & 79 & -41 & -34 \\\\19 & -26 & -4 & 94 & -91 \\\\-53 & 98 & 99 & -55 & -5 \\\\-39 & -35 & 80 & 74 & -98 \\\\89 & 27 & -27 & -64 & -4 \\\\-39 & 0 & -17 & 41 & -11 \\\\34 & 88 & -55 & 47 & 54 \\\\-33 & -81 & 91 & -52 & 8 \\\\-3 & -25 & 58 & -19 & -9 \\end{array}\\right)$" + "$\\left(\\begin{array}{ccccc} -21 & 73 & -25 & -83 & -57 \\\\12 & -79 & -2 & 50 & -98 \\\\-9 & 62 & 95 & -67 & -39 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "A=al.randomA()" ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "a4bcb3f6e87e4794ad181ed7f3b58026", + "model_id": "ee177c6aeaaa402499b9ed6077705858", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntText(value=1, description='m:')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "936c8bd41d43423992cddca6fd403ea9", + "model_id": "9a3031318feb4083bc3eb1e710a5f0c2", "version_major": 2, "version_minor": 0 }, "text/plain": [ - "IntText(value=1, description='m:')" + "IntText(value=1, description='n:')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "52a6fa30ad26499789af8837c0bb2c21", + "model_id": "d2bfd7af429f48cda6f9bc7f9e0ce95b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(Button(description='Run Interact', style=ButtonStyle()), Output()), _dom_classes=('widge…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.dimensionA(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **Nouvelles notations**\n", "\n", "Pour rentrer une matrice on utilise *la syntaxe suivante*\n", "$$A=\\quad [\\quad [ a_{11} , a_{12}, \\ldots, a_{1n} ], \\quad [ a_{21}, a_{22}, \\ldots, a_{2n}]\\quad, \\ldots , \\quad[a_{m1}, a_{m2}, \\ldots, a_{mn}]\\quad].$$\n", "\n", "Comme nous souhaitons différencier les vecteurs colonnes - ceux usuel - des vecteurs lignes, nous les différencions **à partir de maintenant** en utilisant *la syntaxe suivante*\n", "\n", "$$\n", "\\begin{align*}\n", "\\overrightarrow{b}&=\\begin{pmatrix}b_1 \\\\ b_2 \\\\ \\vdots \\\\ b_m\\end{pmatrix}\n", "&&\\Rightarrow b=\\quad [\\quad [ b_{1} ], \\quad [b_{2}], \\quad \\ldots, \\quad [b_m] \\quad]\\\\\n", "\\overrightarrow{v}&=\\begin{pmatrix} v_1 & v_2 & \\cdots v_n\\end{pmatrix}\n", "&&\\Rightarrow v=\\quad[ \\quad v_1, \\quad v_2, \\quad \\ldots, \\quad v_n \\quad ]\n", "\\end{align*}\n", "$$\n", "\n", "---\n", "\n", "Entrez les vecteurs et matrices ci-dessous.\n", "$$\n", "\\begin{pmatrix}\n", "1 & -3 \\\\\n", "3 & 5\n", "\\end{pmatrix} \\hskip1em \\begin{pmatrix}\n", "1 \\\\\n", "2 \n", "\\end{pmatrix}\\hskip1em\\begin{pmatrix}\n", "1 \\\\\n", "0.3\\\\\n", "1/4\n", "\\end{pmatrix}\\hskip1em\\begin{pmatrix}\n", "1 &2 &-1\n", "\\end{pmatrix}\\hskip1em\\begin{pmatrix}\n", "1 & 0 & -1\\\\\n", "0 & -1 & 1\\\\\n", "1 & 1 & 0\n", "\\end{pmatrix}\n", "$$" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.bgc('seashell')\n", "A=[[1],[2]]" ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$\\left(\\begin{array}{c} 1 \\\\2 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.printA(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lorsqu'on travaille avec des systèmes, on s'intéresse à la matrice augmentée - dans laquelle on retrouve la matrice des coefficients $A$ et une colonne additionnelle correspondant aux termes de droite.\n", "\n", "$$\\begin{align*}\n", "\\text{Notation système} \\quad &\\Leftrightarrow \\quad\\text{Notation matricielle}\\\\\n", "\\begin{cases}\n", "a_{11}x_1 + a_{12}x_2&=b_1\\\\\n", "a_{21}x_1 + a_{22}x_2&=b_2\n", "\\end{cases} \\quad &\\Leftrightarrow \\quad \\left(\\begin{array}{cc|c}\n", "a_{11} & a_{12} & b_1\\\\\n", "a_{21} & a_{22} & b_2\n", "\\end{array}\\right)\n", "\\end{align*}\n", "$$\n", "\n", "---\n", "Pour entrer les matrices augmentées des systèmes, en utilisez la syntaxe suivante\n", "\n", "$$\n", "\\begin{align*}\n", "A&=\\quad[\\quad [ a_{11} , a_{12}, \\ldots, a_{1n} ], \\quad [ a_{21}, a_{22}, \\ldots, a_{2n}]\\quad, \\ldots , \\quad[a_{m1}, a_{m2}, \\ldots, a_{mn}]\\quad]\\\\\n", "b&=\\quad[\\quad [b_1], \\quad [b_2], \\ldots, [b_m]\\quad ] \\leftarrow\\text{ceci nous permet de différencier un vecteur colonne d'un vecteur ligne!}\n", "\\end{align*}\n", "$$\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **EXERCICE 1**\n", "Entrez les matrices augmentées des systèmes ci-dessous.\n", "\n", "$$\n", "1) \\quad \\begin{cases}\n", "2x_1 -x_2&=3\\\\\n", "x_1 + x_2&=0,\n", "\\end{cases}\\hskip2em\n", "2)\\quad \\begin{cases}\n", "\\dfrac{1}{3}x_1 + x_2 - x_3&=-6\\\\\n", "x_1 + x_3&=2\\\\\n", "-x_1 + \\dfrac{27}{9}x_2- x_3&=-1,\n", "\\end{cases}\\hskip2em\n", "3)\\quad \\begin{cases}\n", "x_1 - 4x_2=7\n", "\\end{cases}\\hskip2em\n", "4) \\begin{cases}\n", "x_1 &=3\\\\\n", "x_2 &= 4\\\\\n", "x_3 &= -1\\\\\n", "x_4&=0\n", "\\end{cases}\\hskip1em\n", "$$" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.bgc('seashell')\n", "#Entrer la matrice des coeff et le vecteur des termes de droite. Attention aux dimensions!\n", "A=[[1,1], [1,1]]\n", "b=[[1],[1]]" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Le système est\n", "\n" ] }, { "data": { "text/latex": [ "$\\begin{cases}1x_1 + 1x_2=1\\\\1x_1 + 1x_2=1\\\\\\end{cases}$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", " Son écriture matricielle est\n", "\n" ] }, { "data": { "text/latex": [ "$\\left(\\begin{array}{cc| cc} 1 & 1 & 1 \\\\1 & 1 & 1 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "print('Le système est\\n')\n", "\n", "al.printSyst(A,b)\n", "print('\\n')\n", "print(' Son écriture matricielle est\\n')\n", "al.printA(A,b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Concept(s)-clé(s) et théorie\n", "\n", "Il existe trois type d'opérations que l'on peut effectuer sur un système d'équations linéaires, ou sur la matrice augmentée correspondante, sans changer son ensemble de solution. \n", "\n", "Ces opérations sont appelées *opérations élémentaires* \n", "\n", - "1. (Remplacement) Remplacer la ligne $i$ par la ligne obtenue en lui ajoutant un multiple ($\\alpha$) de la ligne $j$. \n", - "2. (Échange) Échanger la ligne $i$ avec la ligne $j$. \n", - "3. (Multiplication par un scalaire) Multiplier tous les coefficients de la ligne $i$ par une constante non-nulle $(\\alpha)$." + "\n", + "1. (Échange) Échanger la ligne $i$ avec la ligne $j$. \n", + "2. (Multiplication par un scalaire) Multiplier tous les coefficients de la ligne $i$ par une constante non-nulle $(\\alpha)$.\n", + "3. (Remplacement) Remplacer la ligne $i$ par la ligne obtenue en lui ajoutant un multiple ($\\alpha$) de la ligne $j$. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### EXEMPLE 1 :\n", "\n", "Entrer la matrice (augmentée) correspondante au système ci-dessous et effectuer les trois opérations suivantes sur la matrice de départ. \n", "\n", - "1. Remplacer la ligne 2 par la ligne obtenue en lui ajoutant 3 fois la ligne $3$.\n", - "2. Échanger la ligne $1$ et la ligne $2$.\n", - "3. Multiplier tous les coefficients de la ligne $2$ par $-\\dfrac{1}{2}$.\n", + "1. Échanger la ligne $1$ et la ligne $2$.\n", + "2. Multiplier tous les coefficients de la ligne $2$ par $-\\dfrac{1}{2}$.\n", + "3. Remplacer la ligne 2 par la ligne obtenue en lui ajoutant 3 fois la ligne $3$. \n", "\n", "Le systèmes est \n", "$$\n", "\\begin{cases}\n", "x_1 -3x_2 + \\dfrac{1}{3}x_3&=0\\\\\n", "x_1 -7 x_3&=2\\\\\n", "-2x_1 + 3x_2 -4x_3&=5\n", "\\end{cases}\n", "$$\n" ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.bgc('seashell')\n", "#Entrer la matrice des coeff et le vecteur des termes de droite. Attention aux dimensions!\n", "A=[[1, 3, 1/3], [1, 0, -7],[-2,3,-4]]\n", "b=[[0],[2],[5]]" ] }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$\\left(\\begin{array}{ccc| cc} 1 & 3 & 0.333 & 0 \\\\1 & 0 & -7 & 2 \\\\-2 & 3 & -4 & 5 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ - "Régler les paramètres\n" + "Régler les paramètres et cliquer sur RUN INTERACT pour effectuer votre opération\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "f951c6e997ae4f039cbc7b790dfd0f3b", + "model_id": "e43b8fb9cd4a43ca9e0b866b05bceef9", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(RadioButtons(description='Opération:', options=('Eij', 'Ei(alpha)', 'Eij(alpha)'), value…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ - "al.printAAug(A,b)\n", + "al.printA(A,b)\n", "al.manualOp(A,b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **EXERCICE 1**\n", "\n", "Parmis les systèmes ci-dessous, lesquels ont le même ensemble de solutions?\n", "\n", "$$\n", "a) \\begin{cases}\n", "3\\times 3\n", "\\end{cases}b) \\begin{cases}\n", "4\\times 4\n", "\\end{cases}c) \\begin{cases}\n", "3\\times 3\n", "\\end{cases}d) \\begin{cases}\n", "4\\times 4\n", "\\end{cases}e) \\begin{cases}\n", "3\\times 3\n", "\\end{cases}\n", "$$" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 2 } diff --git "a/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.5. Matrices Echelonn\303\251es-checkpoint.ipynb" "b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.5-1.6. Matrices Echelonn\303\251es-checkpoint.ipynb" similarity index 64% rename from "Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.5. Matrices Echelonn\303\251es-checkpoint.ipynb" rename to "Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.5-1.6. Matrices Echelonn\303\251es-checkpoint.ipynb" index f6bc1a9..3186bfa 100644 --- "a/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.5. Matrices Echelonn\303\251es-checkpoint.ipynb" +++ "b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.5-1.6. Matrices Echelonn\303\251es-checkpoint.ipynb" @@ -1,330 +1,298 @@ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Concept(s)-clé(s) et théorie\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ " \n", " " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import AL_Fct as al\n", "import numpy as np\n", "import ipywidgets as widgets\n", "import random\n", "\n", "from ipywidgets import interact, interactive, fixed, interact_manual" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### ** EXERCICE 1**\n", + "### **Exercice 1**\n", "\n", - "Trouver la solution du système en échelonnant la matrice augmentée correspondante\n", + "À l'aide des opérations élémentaires, échelonner et réduire les matrices ci-dessous.\n", "\n", "$$\n", - "\\begin{cases}\n", - "\\end{cases}\n", - "$$\n" + "\\begin{pmatrix}\n", + "2 & -1\\\\\n", + "1 &2\n", + "\\end{pmatrix}\\hskip2em\n", + "\\begin{pmatrix}\n", + "\\dfrac{1}{2} & 3 & 0\\\\\n", + "2 & -4 & 6\\\\\n", + "1 & 3 &-1\n", + "\\end{pmatrix}\\hskip2em\n", + "\\begin{pmatrix}\n", + "1 & 0 &1\\\\\n", + "0 & 1 & -1\\\\\n", + "1 & 1 &-1\n", + "\\end{pmatrix}\n", + "$$" ] }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "A=[[2,-1], [1,2]]" + ] + }, + { + "cell_type": "code", + "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Vous allez échelonner la matrice\n" ] }, { "data": { "text/latex": [ - "$\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\4 & 5 & 6 & 0 & 1 & 0 \\\\7 & 8 & 9 & 0 & 0 & 1 \\end{array}\\right)$" + "$\\left(\\begin{array}{cc} 2 & -1 \\\\1 & 2 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Régler les paramètres et évaluer la cellule suivante\n", "Répéter cela jusqu'à obtenir une forme échelonnée réduite\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "f04476e011d244709526299fba48dd5b", + "model_id": "8f22beb9f62f4cdba6fc3da82b889044", "version_major": 2, "version_minor": 0 }, "text/plain": [ "RadioButtons(description='Opération:', options=('Eij', 'Ei(alpha)', 'Eij(alpha)'), value='Eij')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "f1de3bef209141d5a8e554794000c35a", + "model_id": "bc00d64d4a154dbe824417f540e1063e", "version_major": 2, "version_minor": 0 }, "text/plain": [ - "BoundedIntText(value=1, description='Ligne i:', max=3, min=1)" + "BoundedIntText(value=1, description='Ligne i:', max=2, min=1)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "58c5123f244742bf8e73093c77f96d03", + "model_id": "200d9b1e0b9f45abb3f91b43bae2579d", "version_major": 2, "version_minor": 0 }, "text/plain": [ - "BoundedIntText(value=1, description='Ligne j:', max=3, min=1)" + "BoundedIntText(value=1, description='Ligne j:', max=2, min=1)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "0673c0ee0a394dbcb192a888ee4b6638", + "model_id": "4171b37c5ff94c4789b6f4d9b2a5329a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Text(value='1', description='Coeff. alpha:')" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ - "A=[[1,2,3],[4,5,6],[7,8,9]]\n", - "b=[[1,0,0],[0,1,0], [0,0,1]]\n", "print('Vous allez échelonner la matrice')\n", - "al.printAAug(A,b)\n", - "[i,j,r,alpha]= al.manualEch(A,b)\n", - "m=np.concatenate((A,b), axis=1)\n", + "al.printA(A)\n", + "[i,j,r,alpha]= al.manualEch(A)\n", "MatriceList=[A]\n", - "RhSList=[b]" + "m=np.matrix(A)" ] }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/latex": [ - "$\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\4 & 5 & 6 & 0 & 1 & 0 \\\\7 & 8 & 9 & 0 & 0 & 1 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\4 & 5 & 6 & 0 & 1 & 0 \\\\7 & 8 & 9 & 0 & 0 & 1 \\end{array}\\right)$" + "$\\left(\\begin{array}{cc} 2 & -1 \\\\1 & 2 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{cc} 2 & -1 \\\\1 & 2 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{cc} 1 & 2 \\\\2 & -1 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{cc} 1 & 2 \\\\2 & -1 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ - "if alpha.value==0:\n", - " print('Le coefficient alpha doit être non-nul!')\n", - "if r.value=='Eij':\n", - " m=al.Eij(m,i.value-1,j.value-1)\n", - "if r.value=='Ei(alpha)':\n", - " m=al.Ealpha(m,i.value-1,eval(alpha.value))\n", - "if r.value=='Eij(alpha)':\n", - " m=al.Eijalpha(m,i.value-1,j.value-1,eval(alpha.value))\n", - " \n", - "MatriceList.append(m[:,0:len(A[0])])\n", - "RhSList.append(m[:,len(A[0]):])\n", - "\n", - "al.printEquMatricesAug(MatriceList,RhSList)" + "al.echelonnage(i,j,r,alpha,A,m,MatriceList)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### ** VERIFICATION **\n", - "À l'aide des cellules ci-dessous, vous pouvez entrer la matrice (des coefficients ou augmentée) de votre choix et obtenir une forme échelonnée et sa forme échelonnée réduite." + "### **VERIFICATION**\n", + "À l'aide des cellules ci-dessous, vous pouvez entrer la matrice (des coefficients ou augmentée) de votre choix et obtenir une forme échelonnée et sa forme échelonnée réduite.\n", + "\n", + "Pour **les formes échelonnées** on utilise la syntaxe suivante\n", + "\n", + "1. Pour la matrice $A$ : al.echelonMat('E', A)\n", + "2. Pour la matrice augmentée $(A | b)$ : al.echelonMat('E', A, b)\n", + "\n", + "Pour obenir **les formes échelonnées réduites** mettez 'ER' au lieu de 'E'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "A=[[1,2,3,4], [5,6,7,8], [9,10,11,12]]\n", "b=[[-1],[-2],[-3]]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "La matrice est sous la forme échelonnée\n" ] }, { "data": { "text/latex": [ "$\\left(\\begin{array}{ccccc} 1 & 2 & 3 & 4 & -1 \\\\5 & 6 & 7 & 8 & -2 \\\\9 & 10 & 11 & 12 & -3 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccccc} 1 & 2 & 3 & 4 & -1 \\\\0 & 1 & 2 & 3 & -0.75 \\\\0 & 0 & 0 & 0 & 0 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "La matrice est sous la forme échelonnée réduite\n" ] }, { "data": { "text/latex": [ "$\\left(\\begin{array}{cccccc} 1 & 2 & 3 & 4 & -1 & -1 \\\\5 & 6 & 7 & 8 & -2 & -2 \\\\9 & 10 & 11 & 12 & -3 & -3 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccccc} 1 & 0 & -1 & -2 & 0.5 \\\\0 & 1 & 2 & 3 & -0.75 \\\\0 & 0 & 0 & 0 & 0 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "M=al.echelonMat('ER',A,b)" ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import AL_Fct as al\n", - "import numpy as np\n", - "Mat=[[2,2],[-2,3], [1,0]]\n", - "b=[[3],[2],[1]]\n", - "\n", - "Mat=al.echelonMat(Mat, b) #attention différence entre ech [A | b] ou [A]\n", - "Mat=np.array(Mat)\n", - "print(Mat[3:len(Mat),:])\n", - "Mat[3:len(Mat),:]=0\n", - "print(len(Mat), len(Mat[1,:]))\n", - "i=(len(Mat)-1)\n", - "while i>=1:\n", - " print('i=',i)\n", - " while all(abs(Mat[i,:len(Mat[0])-1])<1e-15) and i!=0:#if ligne (or rest of) is zero, take next ligne\n", - " i-=1\n", - " print('here')\n", - " #we have a lign with one non-nul element\n", - " j=i #we can start at pos ij at least the pivot is there\n", - " if abs(Mat[i,j])<1e-15: #if element Aij=0 take next one --> find pivot\n", - " j+=1\n", - " #Aij!=0 and Aij==1 if echelonMat worked\n", - " print('i=',i,'j=',j, 'Mat(i,:)', Mat[i,:]) \n", - " for k in range(i): #put zeros above pivot (which is 1 now)\n", - " print('k=',k)\n", - " Mat=al.Eijalpha(Mat, k,i, -Mat[k,j])\n", - " i-=1\n", - " al.printA(Mat)\n", - "\n", - "print(\"La matrice est sous la forme échelonnée réduite\")\n", - "al.printEquMatrices([MatCoeff, Mat])\n" - ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 2 } diff --git "a/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.7. R\303\251solutions de syst\303\250mes lin\303\251aires-checkpoint.ipynb" "b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.7. R\303\251solutions de syst\303\250mes lin\303\251aires-checkpoint.ipynb" new file mode 100644 index 0000000..2308f6a --- /dev/null +++ "b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/1.7. R\303\251solutions de syst\303\250mes lin\303\251aires-checkpoint.ipynb" @@ -0,0 +1,87 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Concept(s)-clé(s) et théorie\n", + "\n", + "DÉFINITION 1 :\n", + "Soit $B$ une matrice échelonnée. Alors les inconnues (du système linéaire associé) dont la colonne correspondante ne possède pas de pivot sont appelées les inconnues libres. Les inconnues dont la colonne correspondante possède un pivot sont appelées les inconnues principales.\n", + "\n", + "MÉTHODE DE RÉSOLUTION DE SYSTÈMES LINÉAIRES :\n", + "Soit $S$ un système linéaire à $n$ inconnues. Afin de trouver l'ensemble des solutions de $S$, on procède comme suit :\n", + "\n", + "1. Poser A la matrice augmentée du système.\n", + "2. Utiliser la méthode d'élimination de Gauss afin de transformer A en une matrice échelonnée B.\n", + "3. Si la matrice B possède une ligne de la forme $(0 0 ⋯ 0 | c )$ avec $c\\neq 0$, alors le système ne possède aucune solution.\n", + "4. S'il existe n pivots, aucun dans la dernière colonne, alors il existe une unique solution.\n", + "5. S'il existe moins de n pivots, aucun dans la dernière colonne, alors il existe un nombre infini de solutions.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### **EXERCICE 1**\n", + "\n", + "Trouver la solution du système en échelonnant la matrice augmentée correspondante\n", + "\n", + "$$\n", + "\\begin{cases}\n", + "-3x_1 + \\dfrac{1}{3}x_2 -x_3&=0\\\\\n", + "x_1 -4x_2 + x_3&=2\\\\\n", + "x_2 -5 x_3&=-2\n", + "\\end{cases}\n", + "$$\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "A=[[-2,2/3,-1],[1,-2,1],[0,1,-5]]\n", + "b=[[0],[2], [-3]]\n", + "print('Vous allez échelonner la matrice')\n", + "al.printAAug(A,b)\n", + "[i,j,r,alpha]= al.manualEch(A,b)\n", + "m=np.concatenate((A,b), axis=1)\n", + "MatriceList=[A]\n", + "RhSList=[b]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "al.echelonnage(i,j,r,alpha,m,MatriceList,RhSList)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/AL_Fct-checkpoint.py b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/AL_Fct-checkpoint.py index 9854864..958e183 100644 --- a/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/AL_Fct-checkpoint.py +++ b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/AL_Fct-checkpoint.py @@ -1,671 +1,710 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 16:42:29 2019 @author: jecker """ from __future__ import division import numpy as np from IPython.display import display, Latex import matplotlib.pyplot as plt import math import plotly import plotly.plotly as py import plotly.graph_objs as go plotly.offline.init_notebook_mode(connected=True) from IPython.core.magic import register_cell_magic from IPython.display import HTML import ipywidgets as widgets import random from ipywidgets import interact, interactive, fixed, interact_manual @register_cell_magic def bgc(color, cell=None): script = ( "var cell = this.closest('.jp-CodeCell');" "var editor = cell.querySelector('.jp-Editor');" "editor.style.background='{}';" "this.parentNode.removeChild(this)" ).format(color) display(HTML(''.format(script))) ############################################################################### ## PRINTS Equations, systems, matrix def strEq(n,coeff):# Latex str of one equation in format a1x1+ ...+anxn or with coefficients. Eq='' if str(coeff)=='' or coeff==[]: if n==1: Eq=Eq + 'a_1x_1 = b' elif n==2: Eq=Eq + 'a_1x_1 + a_2x_2 = b' else: Eq=Eq + 'a_1x_1 + \ldots + ' + 'a_' + str(n) + 'x_'+ str(n) + '=b' else : if n==1: Eq=Eq + str(round(coeff[0],3) if coeff[0] % 1 else int(coeff[0]))+ 'x_'+str(1) +\ '='+ str(round(coeff[len(coeff)-1],3) if coeff[len(coeff)-1] % 1 else int(coeff[len(coeff)-1])) else: Eq=Eq + str(round(coeff[0],3) if coeff[0] % 1 else int(coeff[0]))+ 'x_'+str(1) for i in range(1,n-1): Eq=Eq + ' + ' + str(round(coeff[i],3) if coeff[i] %1 else int(coeff[i])) + 'x_' + str(i+1) Eq=Eq + ' + ' +str(round(coeff[len(coeff)-2],3) if coeff[len(coeff)-2] % 1 else int(coeff[len(coeff)-2]))\ + 'x_' + str(n) + '=' + str(round(coeff[len(coeff)-1],3) if coeff[len(coeff)-1] % 1 else int(coeff[len(coeff)-1])) return Eq def printEq(coeff,b, *args):# Latex Print of one equation in format a1x1+ ...+anxn or with coefficients. if len(args)==1: n=args[0] else: n=len(coeff) coeff=coeff+b texEq='$' texEq=texEq+ strEq(n,coeff) texEq=texEq + '$' display(Latex(texEq)) def printSyst(A,b, *args):# Latex Print of one system of m equation in format ai1x1+ ...+ainxn=bi or with coeff in MatCoeff. if (len(args)==2) or (len(A)==len(b)): #ensures that MatCoeff has proper dimensions if len(args)==2: m=args[0] n=args[1] else: m=len(A) n=len(A[0]) texSyst='$\\begin{cases}' Eq_list=[] if type(b[0])==list: b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) else: A = [A[i]+[b[i]]for i in range(0,m)] #becomes augmented matrix A=np.array(A) #just in case it's not for i in range(m): if str(A)=='': Eq_i='' if n==1: Eq_i=Eq_i + 'a_{' + str(i+1) + '1}' + 'x_1 = b_' + str(i+1) elif n==2: Eq_i=Eq_i + 'a_{' + str(i+1) + '1}' + 'x_1 + ' + 'a_{' + str(i+1) + '2}' + 'x_2 = b_' + str(i+1) else: Eq_i=Eq_i + 'a_{' + str(i+1) + '1}' + 'x_1 + \ldots +' + 'a_{' + str(i+1) +str(n) + '}' + 'x_'+ str(n) + '=b_' + str(i+1) else: Eq_i=strEq(n,A[i,:]) #attention A is (A|b) Eq_list.append(Eq_i) texSyst=texSyst+ Eq_list[i] + '\\\\' texSyst =texSyst+ '\\end{cases}$' display(Latex(texSyst)) else: print("La matrice des coefficients n'a pas les bonnes dimensions") def texMatrix(*args): #return tex expression of one matrix of A or (A|b) -- or (A|B) VERIFIED OK if len(args)==2: # matrice augmentée A=np.matrix(args[0]).astype(float) m=A.shape[0] b=args[1] #b=[b[i] for i in range(m)] b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) texApre ='\\left(\\begin{array}{' texA = '' for i in np.asarray(A) : texALigne = '' texALigne = texALigne + str(round(i[0],3) if i[0] %1 else int(i[0])) if texA == '' : texApre = texApre + 'c' for j in i[1:m] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) if texA == '' : texApre = texApre + '| c' for j in i[m:] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) texALigne = texALigne + ' \\\\' texA = texA + texALigne texA = texApre + '} ' + texA[:-2] + ' \\end{array}\\right)' elif len(args)==1: #matrice des coefficients A=np.matrix(args[0]).astype(float) texApre ='\\left(\\begin{array}{' texA = '' for i in np.asarray(A) : texALigne = '' texALigne = texALigne + str(round(i[0],3) if i[0] %1 else int(i[0])) if texA == '' : texApre = texApre + 'c' for j in i[1:] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) texALigne = texALigne + ' \\\\' texA = texA + texALigne texA = texApre + '} ' + texA[:-2] + ' \\end{array}\\right)' else: print("Ce n'est pas une matrice des coefficients ni une matrice augmentée") return texA def printA(*args) : #Print matrix VERIFIED OK texA='$'+ texMatrix(*args) + '$' # print(texA) display(Latex(texA)) -def printEquMatrices(*args): # M=[M1, M2, ..., Mn] n>1 VERIFIED OK - texEqu='$' + texMatrix(args[0]) - for i in range(1,len(args)): - texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(args[i]) - texEqu=texEqu+ '$' - display(Latex(texEqu)) + +def printEquMatrices(*args): #list of matrices is M=[M1, M2, ..., Mn] where Mi=(Mi|b) + if len(args)==2: + listOfMatrices=args[0] + listOfRhS=args[1] + texEqu='$' + texMatrix(listOfMatrices[0],listOfRhS[0]) + for i in range(1,len(listOfMatrices)): + texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(listOfMatrices[i], listOfRhS[i]) + texEqu=texEqu+ '$' + display(Latex(texEqu)) + else: + listOfMatrices=args[0] + texEqu='$' + texMatrix(listOfMatrices[0]) + for i in range(1,len(listOfMatrices)): + texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(listOfMatrices[i]) + texEqu=texEqu+ '$' + display(Latex(texEqu)) - -def printEquMatricesAug(listOfMatrices, listOfRhS): #list of matrices is M=[M1, M2, ..., Mn] where Mi=(Mi|b) - texEqu='$' + texMatrixAug(listOfMatrices[0],listOfRhS[0]) - for i in range(1,len(listOfMatrices)): - texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrixAug(listOfMatrices[i], listOfRhS[i]) - texEqu=texEqu+ '$' - display(Latex(texEqu)) #%% Functions to enter smth def EnterInt(n): #function enter integer. while type(n)!=int: try: n=int(n) if n<=0: print("Le nombre ne peut pas être négatif!") print("Entrez à nouveau : ") n=input() except: print("Ce n'est pas un entier!") print("Entrez à nouveau :") n=input() n=int(n) return n def EnterListReal(n): #function enter list of real numbers. coeff=input() while type(coeff)!=list: try: coeff=[float(eval(x)) for x in coeff.split(',')] if len(coeff)!=n+1: print("Vous n'avez pas entré le bon nombre de réels!") print("Entrez à nouveau : ") coeff=input() except: print("Ce n'est pas le bon format!") print("Entrez à nouveau") coeff=input() #coeff[abs(coeff)<1e-15]=0 #ensures that 0 is 0. return coeff #%%Verify if sol is the solution of the equation with coefficients coeff def SolOfEq(sol,coeff, i): A = np.asarray(coeff[0:len(coeff)-1]) if abs(np.dot(A,sol)-coeff[len(coeff)-1])<1e-10: print("La suite entrée est une solution de l'équation", i) else: print("La suite entrée n'est pas une solution de l'équation",i) return abs(np.dot(A,sol)-coeff[len(coeff)-1])<1e-10 def SolOfSyst(solution,A,b): A = [A[i]+[b[i]] for i in range(0,len(A))] A=np.array(A) isSol=[SolOfEq(solution, A[i,:],i+1) for i in range(0,len(A))] if all(isSol[i]==True for i in range(len(isSol))): print("C'est une solution du système") else: print("Ce n'est pas une solution du système") #%%Plots using plotly def Plot2DSys(xL,xR,p,A,b): # small values for p allows for dots to be seen A = [A[i]+[b[i]] for i in range(0,len(A))] A=np.array(A) t=np.linspace(xL,xR,p) legend=[] data=[] for i in range(1,len(A)+1): if (abs(A[i-1,1])) > abs (A[i-1,0]) : #p0=[0,A[i-1,2]/A[i-1,1]] #p1=[1,(A[i-1,2]-A[i-1,0])/A[i-1,1]] trace=go.Scatter(x=t, y= (A[i-1,2]-A[i-1,0]*t)/A[i-1,1], name='Droite %d'%i) else : trace=go.Scatter(x=(A[i-1,2]-A[i-1,1]*t)/A[i-1,0], y= t, name='Droite %d'%i) data.append(trace) fig = go.Figure(data=data) plotly.offline.iplot(fig) def Plot3DSys(xL,xR,p,A,b): # small values for p allows for dots to be seen A = [A[i]+[b[i]] for i in range(0,len(A))] A=np.array(A) gr='rgb(102,255,102)' org='rgb(255,117,26)' red= 'rgb(255,0,0)' blue='rgb(51, 214, 255)' colors =[blue, gr, org] s = np.linspace(xL, xR ,p) t = np.linspace(xL, xR, p) tGrid, sGrid = np.meshgrid(s, t) data=[] for i in range(0, len(A)): colorscale=[[0.0,colors[i]], [0.1, colors[i]], [0.2, colors[i]], [0.3, colors[i]], [0.4, colors[i]], [0.5, colors[i]], [0.6, colors[i]], [0.7, colors[i]], [0.8, colors[i]], [0.9, colors[i]], [1.0, colors[i]]] j=i+1 if (abs(A[i,2])) > abs (A[i,1]) : # z en fonction de x,y x = sGrid y = tGrid surface = go.Surface(x=x, y=y, z=(A[i,3]-A[i,0]*x -A[i,1]*y)/A[i,2], showscale=False, colorscale=colorscale, opacity=1, name='Plan %d' %j) elif (A[i,2]==0 and A[i,1]==0): # x =b y = sGrid z = tGrid surface = go.Surface(x=A[i,3]-A[i,1]*y, y=y, z=z, showscale=False, colorscale=colorscale, opacity=1, name='Plan %d' %j) else:# y en fonction de x,z x = sGrid z = tGrid surface = go.Surface(x=x, y=(A[i,3]-A[i,0]*x -A[i,2]*z)/A[i,1], z=z, showscale=False, colorscale=colorscale, opacity=1, name='Plan %d' %j) data.append(surface) layout = go.Layout( showlegend=True, #not there WHY???? legend=dict(orientation="h"), autosize=True, width=800, height=800, scene=go.Scene( xaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), yaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), zaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ) ) ) fig = go.Figure(data=data, layout=layout) plotly.offline.iplot(fig) #%%Echelonnage def echZero(indice, M): #echelonne la matrice pour mettre les zeros dans les lignes du bas. M (matrice ou array) et Mat (list) pas le même format. Mat=M[indice==False,:].ravel() Mat=np.concatenate([Mat,M[indice==True,:].ravel()]) Mat=Mat.reshape(len(M), len(M[0,:])) return Mat def Eij(M, i,j): #matrice elementaire, echange la ligne i avec la ligne j M=np.array(M) M[[i,j],:]=M[[j,i],:] return M def Ealpha(M, i, alpha): # matrice elementaire, multiple la ligne i par le scalaire alpha M=np.array(M) M[i,:]=alpha*M[i,:] return M def Eijalpha(M, i,j, alpha): # matrice elementaire, AJOUTE à la ligne i alpha *ligne j. Attention alpha + ou - M=np.array(M) M[i,:]=M[i,:] + alpha *M[j,:] return M def echelonMat(ech,*args): #Nous donne la matrice echelonnée 'E' ou reduite 'ER' d'une matrice des coeffs. ou augmentée. if len(args)==2: # matrice augmentée A=np.matrix(args[0]).astype(float) m=A.shape[0] b=args[1] if type(b[0])==list: b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) else: b=[b[i] for i in range(m)] A = [A[i]+[b[i]]for i in range(0,m)] else: # matrice coeff A=np.matrix(args[0]).astype(float) m=A.shape[0] b=np.zeros(m) A=np.concatenate((A,b), axis=1) if ech=='E': #Echelonnée Mat=np.array(A) Mat=Mat.astype(float) # in case the array in int instead of float. numPivot=0 for i in range(len(Mat)): j=i while all(abs(Mat[j:,i])<1e-15) and j!=len(Mat[0,:])-1: #if column (or rest of) is 0, take next j+=1 if j==len(Mat[0,:])-1: if len(Mat[0,:])>j: Mat[i+1:len(Mat),:]=0 print("La matrice est sous la forme échelonnée") printEquMatrices(np.asmatrix(A), np.asmatrix(Mat)) break if abs(Mat[i,j])<1e-15: Mat[i,j]=0 zero=abs(Mat[i:,j])<1e-15 M= echZero(zero,Mat[i:,:] ) Mat[i:,:]=M Mat=Ealpha(Mat, i,1/Mat[i,j] ) #normalement Mat[i,j]!=0 for k in range(i+1,len(A)): Mat=Eijalpha(Mat, k,i, -Mat[k,j]) #Mat[k,:]=[0 if abs(Mat[k,l])<1e-15 else Mat[k,l] for l in range(len(MatCoeff[0,:]))] numPivot+=1 Mat[abs(Mat)<1e-15]=0 #printA(np.array(Mat)) elif ech=='ER': # Echelonnée réduite Mat=np.array(A) Mat=Mat.astype(float) # in case the array in int instead of float. numPivot=0 for i in range(len(Mat)): j=i while all(abs(Mat[j:,i])<1e-15) and j!=len(Mat[0,:])-1: #if column (or rest of) is zero, take next column j+=1 if j==len(Mat[0,:])-1: #ADD ZERO LINES BELOW!!!!!! if len(Mat[0,:])>j: Mat[i+1:len(Mat),:]=0 print("La matrice est sous la forme échelonnée") printEquMatrices(np.asmatrix(A), np.asmatrix(Mat)) break if abs(Mat[i,j])<1e-15: Mat[i,j]=0 zero=abs(Mat[i:,j])<1e-15 M= echZero(zero,Mat[i:,:] ) Mat[i:,:]=M Mat=Ealpha(Mat, i,1/Mat[i,j] ) #normalement Mat[i,j]!=0 for k in range(i+1,len(A)): Mat=Eijalpha(Mat, k,i, -Mat[k,j]) #Mat[k,:]=[0 if abs(Mat[k,l])<1e-15 else Mat[k,l] for l in range(len(MatCoeff[0,:]))] numPivot+=1 Mat[abs(Mat)<1e-15]=0 Mat=np.array(Mat) MatAugm=np.concatenate((A,b), axis=1) # MatAugm = [A[i]+[b[i]] for i in range(0,len(A))] i=(len(Mat)-1) while i>=1: while all(abs(Mat[i,:len(Mat[0])-1])<1e-15) and i!=0:#if ligne (or rest of) is zero, take next ligne i-=1 #we have a lign with one non-nul element j=i #we can start at pos ij at least the pivot is there if abs(Mat[i,j])<1e-15: #if element Aij=0 take next one --> find pivot j+=1 #Aij!=0 and Aij==1 if echelonMat worked for k in range(i): #put zeros above pivot (which is 1 now) Mat=Eijalpha(Mat, k,i, -Mat[k,j]) i-=1 #printA(Mat) print("La matrice est sous la forme échelonnée réduite") printEquMatrices(MatAugm, Mat) return np.asmatrix(Mat) -def echelonMatCoeff(A): #take echelonMAt but without b. - b= [0 for i in range(len(A))] - Mat = [A[i]+[b[i]] for i in range(0,len(A))] - Mat=np.array(Mat) - Mat=Mat.astype(float) # in case the array in int instead of float. - numPivot=0 - for i in range(len(Mat)): - j=i - while all(abs(Mat[j:,i])<1e-15) and j!=len(Mat[0,:])-1: #if column (or rest of) is zero, take next column - j+=1 - if j==len(Mat[0,:])-1: - #ADD ZERO LINES BELOW!!!!!! - if len(Mat[0,:])>j: - Mat[i+1:len(Mat),:]=0 - print("La matrice est sous la forme échelonnée") - printEquMatrices(np.asmatrix(A), np.asmatrix(Mat[:, :len(A[0])])) - break - if abs(Mat[i,j])<1e-15: - Mat[i,j]=0 - zero=abs(Mat[i:,j])<1e-15 - M= echZero(zero,Mat[i:,:] ) - Mat[i:,:]=M - Mat=Ealpha(Mat, i,1/Mat[i,j] ) #normalement Mat[i,j]!=0 - for k in range(i+1,len(A)): - Mat=Eijalpha(Mat, k,i, -Mat[k,j]) - #Mat[k,:]=[0 if abs(Mat[k,l])<1e-15 else Mat[k,l] for l in range(len(MatCoeff[0,:]))] - numPivot+=1 - Mat[abs(Mat)<1e-15]=0 - #printA(np.asmatrix(Mat[:, :len(A[0])])) - return np.asmatrix(Mat) - -def echelonRedMat(A, b): - Mat=echelonMat('ER',A,b) - Mat=np.array(Mat) - MatAugm=np.concatenate((A,b), axis=1) - # MatAugm = [A[i]+[b[i]] for i in range(0,len(A))] - i=(len(Mat)-1) - while i>=1: - while all(abs(Mat[i,:len(Mat[0])-1])<1e-15) and i!=0:#if ligne (or rest of) is zero, take next ligne - i-=1 - #we have a lign with one non-nul element - j=i #we can start at pos ij at least the pivot is there - if abs(Mat[i,j])<1e-15: #if element Aij=0 take next one --> find pivot - j+=1 - #Aij!=0 and Aij==1 if echelonMat worked - for k in range(i): #put zeros above pivot (which is 1 now) - Mat=Eijalpha(Mat, k,i, -Mat[k,j]) - i-=1 - printA(Mat) - print("La matrice est sous la forme échelonnée réduite") - printEquMatrices(MatAugm, Mat) - return np.asmatrix(Mat) #Generate random matrix def randomA(): n=random.randint(1,10) m=random.randint(1,10) A=np.empty([m,n],dtype=int) A=[[random.randint(-100,100) for i in range(n)] for j in range(m)] printA(A) return np.matrix(A) def dimensionA(A): m=widgets.IntText( value=1, step=1, description='m:', disabled=False ) n=widgets.IntText( value=1, step=1, - description='n:', + description='m:', disabled=False ) display(m) display(n) def f(): if m.value==A.shape[0] and n.value==A.shape[1]: print('Correcte!') else: print('Incorrecte, entrez de nouvelles valeurs') out=interact_manual(f) def manualEch(*args): if len(args)==2: # matrice augmentée A=np.matrix(args[0]).astype(float) m=A.shape[0] b=args[1] #b=[b[i] for i in range(m)] if type(b[0])==list: b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) else: b=[b[i] for i in range(m)] A = [A[i]+[b[i]]for i in range(0,m)] else: A=np.matrix(args[0]).astype(float) m=A.shape[0] A=np.array(A) #just in case it's not j=widgets.BoundedIntText( value=1, min=1, max=m, step=1, description='Ligne j:', disabled=False ) i=widgets.BoundedIntText( value=1, min=1, max=m, step=1, description='Ligne i:', disabled=False ) r=widgets.RadioButtons( options=['Eij', 'Ei(alpha)', 'Eij(alpha)'], description='Opération:', disabled=False ) alpha=widgets.Text( value='1', description='Coeff. alpha:', disabled=False ) print("Régler les paramètres et évaluer la cellule suivante") print("Répéter cela jusqu'à obtenir une forme échelonnée réduite") display(r) display(i) display(j) display(alpha) return i,j,r,alpha +def echelonnage(i,j,r,alpha,A,m,*args): #1.5-1.6 Matrice echelonnées + if alpha.value==0: + print('Le coefficient alpha doit être non-nul!') + if r.value=='Eij': + m=Eij(m,i.value-1,j.value-1) + if r.value=='Ei(alpha)': + m=Ealpha(m,i.value-1,eval(alpha.value)) + if r.value=='Eij(alpha)': + m=Eijalpha(m,i.value-1,j.value-1,eval(alpha.value)) + if len(args)==2: + MatriceList=args[0] + RhSList=args[1] + MatriceList.append(m[:,0:len(A[0])]) + printEquMatrices(MatriceList,RhSList) + else: + MatriceList=args[0] + MatriceList.append(m[:,0:len(A[0])]) + printEquMatrices(MatriceList) + + def manualOp(*args): if len(args)==2: # matrice augmentée A=np.matrix(args[0]).astype(float) m=A.shape[0] b=args[1] #b=[b[i] for i in range(m)] if type(b[0])==list: b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) else: b=[b[i] for i in range(m)] A = [A[i]+[b[i]]for i in range(0,m)] else: A=np.matrix(args[0]).astype(float) m=A.shape[0] A=np.array(A) #just in case it's not j=widgets.BoundedIntText( value=1, min=1, max=m, step=1, description='Ligne j:', disabled=False ) i=widgets.BoundedIntText( value=1, min=1, max=m, step=1, description='Ligne i:', disabled=False ) r=widgets.RadioButtons( options=['Eij', 'Ei(alpha)', 'Eij(alpha)'], description='Opération:', disabled=False ) alpha=widgets.Text( value='1', description='Coeff. alpha:', disabled=False ) print("Régler les paramètres et cliquer sur RUN INTERACT pour effectuer votre opération") def f(r,i,j,alpha): m=np.concatenate((A,b), axis=1) MatriceList=[A] RhSList=[b] if alpha==0: print('Le coefficient alpha doit être non-nul!') if r=='Eij': m=Eij(m,i-1,j-1) if r=='Ei(alpha)': m=Ealpha(m,i.value-1,eval(alpha)) if r=='Eij(alpha)': m=Eijalpha(m,i-1,j-1,eval(alpha)) MatriceList.append(m[:,0:len(A[0])]) RhSList.append(m[:,len(A[0]):]) printEquMatricesAug(MatriceList,RhSList) interact_manual(f,r=r,i=i,j=j,alpha=alpha) -#OBSOLETE +########################################OBSOLETE +def printEquMatricesAug(listOfMatrices, listOfRhS): #list of matrices is M=[M1, M2, ..., Mn] where Mi=(Mi|b) + texEqu='$' + texMatrixAug(listOfMatrices[0],listOfRhS[0]) + for i in range(1,len(listOfMatrices)): + texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrixAug(listOfMatrices[i], listOfRhS[i]) + texEqu=texEqu+ '$' + display(Latex(texEqu)) + +def echelonMatCoeff(A): #take echelonMAt but without b. + b= [0 for i in range(len(A))] + Mat = [A[i]+[b[i]] for i in range(0,len(A))] + Mat=np.array(Mat) + Mat=Mat.astype(float) # in case the array in int instead of float. + numPivot=0 + for i in range(len(Mat)): + j=i + while all(abs(Mat[j:,i])<1e-15) and j!=len(Mat[0,:])-1: #if column (or rest of) is zero, take next column + j+=1 + if j==len(Mat[0,:])-1: + #ADD ZERO LINES BELOW!!!!!! + if len(Mat[0,:])>j: + Mat[i+1:len(Mat),:]=0 + print("La matrice est sous la forme échelonnée") + printEquMatrices(np.asmatrix(A), np.asmatrix(Mat[:, :len(A[0])])) + break + if abs(Mat[i,j])<1e-15: + Mat[i,j]=0 + zero=abs(Mat[i:,j])<1e-15 + M= echZero(zero,Mat[i:,:] ) + Mat[i:,:]=M + Mat=Ealpha(Mat, i,1/Mat[i,j] ) #normalement Mat[i,j]!=0 + for k in range(i+1,len(A)): + Mat=Eijalpha(Mat, k,i, -Mat[k,j]) + #Mat[k,:]=[0 if abs(Mat[k,l])<1e-15 else Mat[k,l] for l in range(len(MatCoeff[0,:]))] + numPivot+=1 + Mat[abs(Mat)<1e-15]=0 + #printA(np.asmatrix(Mat[:, :len(A[0])])) + return np.asmatrix(Mat) + +def echelonRedMat(A, b): + Mat=echelonMat('ER',A,b) + Mat=np.array(Mat) + MatAugm=np.concatenate((A,b), axis=1) + # MatAugm = [A[i]+[b[i]] for i in range(0,len(A))] + i=(len(Mat)-1) + while i>=1: + while all(abs(Mat[i,:len(Mat[0])-1])<1e-15) and i!=0:#if ligne (or rest of) is zero, take next ligne + i-=1 + #we have a lign with one non-nul element + j=i #we can start at pos ij at least the pivot is there + if abs(Mat[i,j])<1e-15: #if element Aij=0 take next one --> find pivot + j+=1 + #Aij!=0 and Aij==1 if echelonMat worked + for k in range(i): #put zeros above pivot (which is 1 now) + Mat=Eijalpha(Mat, k,i, -Mat[k,j]) + i-=1 + printA(Mat) + print("La matrice est sous la forme échelonnée réduite") + printEquMatrices(MatAugm, Mat) + return np.asmatrix(Mat) + def printEquMatricesOLD(listOfMatrices): #list of matrices is M=[M1, M2, ..., Mn] texEqu='$' + texMatrix(listOfMatrices[0]) for i in range(1,len(listOfMatrices)): texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(listOfMatrices[i]) texEqu=texEqu+ '$' display(Latex(texEqu)) def texMatrixAug(A,b): #return tex expression of one matrix (A|b) where b can also be a matrix m=len(A[0]) A=np.concatenate((A,b), axis=1) texApre ='\\left(\\begin{array}{' texA = '' for i in np.asarray(A) : texALigne = '' texALigne = texALigne + str(round(i[0],3) if i[0] %1 else int(i[0])) if texA == '' : texApre = texApre + 'c' for j in i[1:m] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) if texA == '' : texApre = texApre + '| c' for j in i[m:] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) texALigne = texALigne + ' \\\\' texA = texA + texALigne texA = texApre + '} ' + texA[:-2] + ' \\end{array}\\right)' return texA def printAAug(A,b) : #Print matrix (A|b) texA='$'+ texMatrixAug(A,b) + '$' # print(texA) display(Latex(texA)) - \ No newline at end of file + + +def printEquMatricesOLD(*args): # M=[M1, M2, ..., Mn] n>1 VERIFIED OK + texEqu='$' + texMatrix(args[0]) + for i in range(1,len(args)): + texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(args[i]) + texEqu=texEqu+ '$' + display(Latex(texEqu)) \ No newline at end of file diff --git a/Chapitre 1 - Systemes equations lineaires/1.3-4. Notation Matricielle.ipynb b/Chapitre 1 - Systemes equations lineaires/1.3-4. Notation Matricielle.ipynb index 5ec47b1..ecb6cf6 100644 --- a/Chapitre 1 - Systemes equations lineaires/1.3-4. Notation Matricielle.ipynb +++ b/Chapitre 1 - Systemes equations lineaires/1.3-4. Notation Matricielle.ipynb @@ -1,530 +1,563 @@ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Concept(s)-clé(s) et théorie\n", "\n", "On considère un système d'équations linéaires aux inconnues $x_1,\\ldots,x_n$\n", "\n", "$$S=\\left\\{\\begin{array}{ccccccc}\n", "a_{11}x_1 &+a_{12}x_2 & + &\\cdots &+a_{1n}x_n &= &b_1 \\\\\n", "a_{21}x_1 &+a_{22}x_2 & + &\\cdots &+a_{2n}x_n &= &b_2 \\\\\n", "\\vdots & & & &\\vdots & \\vdots &\\vdots \\\\\n", "a_{m1}x_1 &+a_{m2}x_2 & + &\\cdots &+a_{mn}x_n &= &b_m\n", "\\end{array},\\right. $$\n", "\n", "où $a_{ij},b_i\\in \\mathbb{R}$ pour tout $1\\leq i\\leq m$ et tout $1\\leq j\\leq n.$ \n", "\n", "Le système $S$ peut s'écrire sous forme matricielle $A\\overrightarrow{x}=\\overrightarrow{b}$ où la matrice $A$ est appelée *la matrice des coefficients* et $\\overrightarrow{x}$ et $\\overrightarrow{b}$ sont des vecteurs contant les composantes $x_i$ et $b_i$ respectivement. \n", "\n", "Plus précisemment\n", "$$A=\\begin{pmatrix}\n", "a_{11} & a_{12} & \\cdots & a_{1n}\\\\\n", "a_{21} & a_{22} &\\cdots & a_{2n}\\\\\n", "\\vdots & \\vdots & \\ddots & \\vdots\\\\\n", "a_{m1} & a_{m2} & \\cdots & a_{mn}\n", "\\end{pmatrix},\\hskip1em\n", "\\overrightarrow{x}=\\begin{pmatrix}\n", "x_1\\\\\n", "x_2\\\\\n", "\\vdots\\\\\n", "x_n\n", "\\end{pmatrix},\\hskip1em\n", "\\overrightarrow{b}=\n", "\\begin{pmatrix}\n", "b_1\\\\\n", "b_2\\\\\n", "\\vdots\\\\\n", "b_m\n", "\\end{pmatrix},\n", "$$\n", "\n", "---\n", "\n", "La matrice $A$ est de taille $m\\times n$ où **m correspond au nombre de lignes** et **n au nombre de colonnes**.\n", "Le vecteur $\\overrightarrow{x}$ est de taille $n\\times 1$ et le vecteur $\\overrightarrow{b}$ de taille $m\\times 1$.\n", "\n" ] }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 1, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/html": [ + " \n", + " " + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "import AL_Fct as al\n", "import numpy as np\n", "import ipywidgets as widgets\n", "import random\n", "\n", "from ipywidgets import interact, interactive, fixed, interact_manual" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **EXERCICE 1**\n", "\n", "Ci-dessous est générée une matrice $A$ de taille $m\\times n$. Trouver la dimension de la matrice en remplissant les deux champs dans lesquels vous pouvez rentrer une valeur pour $m$ et $n$. \n", "\n", "Vérifier en cliquant sur **Run Interact**" ] }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/latex": [ - "$\\left(\\begin{array}{ccccc} 63 & -78 & -14 & -77 & 73 \\\\54 & 5 & 79 & -41 & -34 \\\\19 & -26 & -4 & 94 & -91 \\\\-53 & 98 & 99 & -55 & -5 \\\\-39 & -35 & 80 & 74 & -98 \\\\89 & 27 & -27 & -64 & -4 \\\\-39 & 0 & -17 & 41 & -11 \\\\34 & 88 & -55 & 47 & 54 \\\\-33 & -81 & 91 & -52 & 8 \\\\-3 & -25 & 58 & -19 & -9 \\end{array}\\right)$" + "$\\left(\\begin{array}{ccccc} -21 & 73 & -25 & -83 & -57 \\\\12 & -79 & -2 & 50 & -98 \\\\-9 & 62 & 95 & -67 & -39 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "A=al.randomA()" ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "a4bcb3f6e87e4794ad181ed7f3b58026", + "model_id": "ee177c6aeaaa402499b9ed6077705858", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntText(value=1, description='m:')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "936c8bd41d43423992cddca6fd403ea9", + "model_id": "9a3031318feb4083bc3eb1e710a5f0c2", "version_major": 2, "version_minor": 0 }, "text/plain": [ - "IntText(value=1, description='m:')" + "IntText(value=1, description='n:')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "52a6fa30ad26499789af8837c0bb2c21", + "model_id": "d2bfd7af429f48cda6f9bc7f9e0ce95b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(Button(description='Run Interact', style=ButtonStyle()), Output()), _dom_classes=('widge…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.dimensionA(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **Nouvelles notations**\n", "\n", "Pour rentrer une matrice on utilise *la syntaxe suivante*\n", "$$A=\\quad [\\quad [ a_{11} , a_{12}, \\ldots, a_{1n} ], \\quad [ a_{21}, a_{22}, \\ldots, a_{2n}]\\quad, \\ldots , \\quad[a_{m1}, a_{m2}, \\ldots, a_{mn}]\\quad].$$\n", "\n", "Comme nous souhaitons différencier les vecteurs colonnes - ceux usuel - des vecteurs lignes, nous les différencions **à partir de maintenant** en utilisant *la syntaxe suivante*\n", "\n", "$$\n", "\\begin{align*}\n", "\\overrightarrow{b}&=\\begin{pmatrix}b_1 \\\\ b_2 \\\\ \\vdots \\\\ b_m\\end{pmatrix}\n", "&&\\Rightarrow b=\\quad [\\quad [ b_{1} ], \\quad [b_{2}], \\quad \\ldots, \\quad [b_m] \\quad]\\\\\n", "\\overrightarrow{v}&=\\begin{pmatrix} v_1 & v_2 & \\cdots v_n\\end{pmatrix}\n", "&&\\Rightarrow v=\\quad[ \\quad v_1, \\quad v_2, \\quad \\ldots, \\quad v_n \\quad ]\n", "\\end{align*}\n", "$$\n", "\n", "---\n", "\n", "Entrez les vecteurs et matrices ci-dessous.\n", "$$\n", "\\begin{pmatrix}\n", "1 & -3 \\\\\n", "3 & 5\n", "\\end{pmatrix} \\hskip1em \\begin{pmatrix}\n", "1 \\\\\n", "2 \n", "\\end{pmatrix}\\hskip1em\\begin{pmatrix}\n", "1 \\\\\n", "0.3\\\\\n", "1/4\n", "\\end{pmatrix}\\hskip1em\\begin{pmatrix}\n", "1 &2 &-1\n", "\\end{pmatrix}\\hskip1em\\begin{pmatrix}\n", "1 & 0 & -1\\\\\n", "0 & -1 & 1\\\\\n", "1 & 1 & 0\n", "\\end{pmatrix}\n", "$$" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.bgc('seashell')\n", "A=[[1],[2]]" ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$\\left(\\begin{array}{c} 1 \\\\2 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.printA(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lorsqu'on travaille avec des systèmes, on s'intéresse à la matrice augmentée - dans laquelle on retrouve la matrice des coefficients $A$ et une colonne additionnelle correspondant aux termes de droite.\n", "\n", "$$\\begin{align*}\n", "\\text{Notation système} \\quad &\\Leftrightarrow \\quad\\text{Notation matricielle}\\\\\n", "\\begin{cases}\n", "a_{11}x_1 + a_{12}x_2&=b_1\\\\\n", "a_{21}x_1 + a_{22}x_2&=b_2\n", "\\end{cases} \\quad &\\Leftrightarrow \\quad \\left(\\begin{array}{cc|c}\n", "a_{11} & a_{12} & b_1\\\\\n", "a_{21} & a_{22} & b_2\n", "\\end{array}\\right)\n", "\\end{align*}\n", "$$\n", "\n", "---\n", "Pour entrer les matrices augmentées des systèmes, en utilisez la syntaxe suivante\n", "\n", "$$\n", "\\begin{align*}\n", "A&=\\quad[\\quad [ a_{11} , a_{12}, \\ldots, a_{1n} ], \\quad [ a_{21}, a_{22}, \\ldots, a_{2n}]\\quad, \\ldots , \\quad[a_{m1}, a_{m2}, \\ldots, a_{mn}]\\quad]\\\\\n", "b&=\\quad[\\quad [b_1], \\quad [b_2], \\ldots, [b_m]\\quad ] \\leftarrow\\text{ceci nous permet de différencier un vecteur colonne d'un vecteur ligne!}\n", "\\end{align*}\n", "$$\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **EXERCICE 1**\n", "Entrez les matrices augmentées des systèmes ci-dessous.\n", "\n", "$$\n", "1) \\quad \\begin{cases}\n", "2x_1 -x_2&=3\\\\\n", "x_1 + x_2&=0,\n", "\\end{cases}\\hskip2em\n", "2)\\quad \\begin{cases}\n", "\\dfrac{1}{3}x_1 + x_2 - x_3&=-6\\\\\n", "x_1 + x_3&=2\\\\\n", "-x_1 + \\dfrac{27}{9}x_2- x_3&=-1,\n", "\\end{cases}\\hskip2em\n", "3)\\quad \\begin{cases}\n", "x_1 - 4x_2=7\n", "\\end{cases}\\hskip2em\n", "4) \\begin{cases}\n", "x_1 &=3\\\\\n", "x_2 &= 4\\\\\n", "x_3 &= -1\\\\\n", "x_4&=0\n", "\\end{cases}\\hskip1em\n", "$$" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.bgc('seashell')\n", "#Entrer la matrice des coeff et le vecteur des termes de droite. Attention aux dimensions!\n", "A=[[1,1], [1,1]]\n", "b=[[1],[1]]" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Le système est\n", "\n" ] }, { "data": { "text/latex": [ "$\\begin{cases}1x_1 + 1x_2=1\\\\1x_1 + 1x_2=1\\\\\\end{cases}$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", " Son écriture matricielle est\n", "\n" ] }, { "data": { "text/latex": [ "$\\left(\\begin{array}{cc| cc} 1 & 1 & 1 \\\\1 & 1 & 1 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "print('Le système est\\n')\n", "\n", "al.printSyst(A,b)\n", "print('\\n')\n", "print(' Son écriture matricielle est\\n')\n", "al.printA(A,b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Concept(s)-clé(s) et théorie\n", "\n", "Il existe trois type d'opérations que l'on peut effectuer sur un système d'équations linéaires, ou sur la matrice augmentée correspondante, sans changer son ensemble de solution. \n", "\n", "Ces opérations sont appelées *opérations élémentaires* \n", "\n", - "1. (Remplacement) Remplacer la ligne $i$ par la ligne obtenue en lui ajoutant un multiple ($\\alpha$) de la ligne $j$. \n", - "2. (Échange) Échanger la ligne $i$ avec la ligne $j$. \n", - "3. (Multiplication par un scalaire) Multiplier tous les coefficients de la ligne $i$ par une constante non-nulle $(\\alpha)$." + "\n", + "1. (Échange) Échanger la ligne $i$ avec la ligne $j$. \n", + "2. (Multiplication par un scalaire) Multiplier tous les coefficients de la ligne $i$ par une constante non-nulle $(\\alpha)$.\n", + "3. (Remplacement) Remplacer la ligne $i$ par la ligne obtenue en lui ajoutant un multiple ($\\alpha$) de la ligne $j$. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### EXEMPLE 1 :\n", "\n", "Entrer la matrice (augmentée) correspondante au système ci-dessous et effectuer les trois opérations suivantes sur la matrice de départ. \n", "\n", - "1. Remplacer la ligne 2 par la ligne obtenue en lui ajoutant 3 fois la ligne $3$.\n", - "2. Échanger la ligne $1$ et la ligne $2$.\n", - "3. Multiplier tous les coefficients de la ligne $2$ par $-\\dfrac{1}{2}$.\n", + "1. Échanger la ligne $1$ et la ligne $2$.\n", + "2. Multiplier tous les coefficients de la ligne $2$ par $-\\dfrac{1}{2}$.\n", + "3. Remplacer la ligne 2 par la ligne obtenue en lui ajoutant 3 fois la ligne $3$. \n", "\n", "Le systèmes est \n", "$$\n", "\\begin{cases}\n", "x_1 -3x_2 + \\dfrac{1}{3}x_3&=0\\\\\n", "x_1 -7 x_3&=2\\\\\n", "-2x_1 + 3x_2 -4x_3&=5\n", "\\end{cases}\n", "$$\n" ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "al.bgc('seashell')\n", "#Entrer la matrice des coeff et le vecteur des termes de droite. Attention aux dimensions!\n", "A=[[1, 3, 1/3], [1, 0, -7],[-2,3,-4]]\n", "b=[[0],[2],[5]]" ] }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$\\left(\\begin{array}{ccc| cc} 1 & 3 & 0.333 & 0 \\\\1 & 0 & -7 & 2 \\\\-2 & 3 & -4 & 5 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ - "Régler les paramètres\n" + "Régler les paramètres et cliquer sur RUN INTERACT pour effectuer votre opération\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "f951c6e997ae4f039cbc7b790dfd0f3b", + "model_id": "e43b8fb9cd4a43ca9e0b866b05bceef9", "version_major": 2, "version_minor": 0 }, "text/plain": [ "interactive(children=(RadioButtons(description='Opération:', options=('Eij', 'Ei(alpha)', 'Eij(alpha)'), value…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ - "al.printAAug(A,b)\n", + "al.printA(A,b)\n", "al.manualOp(A,b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **EXERCICE 1**\n", "\n", "Parmis les systèmes ci-dessous, lesquels ont le même ensemble de solutions?\n", "\n", "$$\n", "a) \\begin{cases}\n", "3\\times 3\n", "\\end{cases}b) \\begin{cases}\n", "4\\times 4\n", "\\end{cases}c) \\begin{cases}\n", "3\\times 3\n", "\\end{cases}d) \\begin{cases}\n", "4\\times 4\n", "\\end{cases}e) \\begin{cases}\n", "3\\times 3\n", "\\end{cases}\n", "$$" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 2 } diff --git "a/Chapitre 1 - Systemes equations lineaires/1.5. Matrices Echelonn\303\251es.ipynb" "b/Chapitre 1 - Systemes equations lineaires/1.5-1.6. Matrices Echelonn\303\251es.ipynb" similarity index 64% rename from "Chapitre 1 - Systemes equations lineaires/1.5. Matrices Echelonn\303\251es.ipynb" rename to "Chapitre 1 - Systemes equations lineaires/1.5-1.6. Matrices Echelonn\303\251es.ipynb" index f6bc1a9..3186bfa 100644 --- "a/Chapitre 1 - Systemes equations lineaires/1.5. Matrices Echelonn\303\251es.ipynb" +++ "b/Chapitre 1 - Systemes equations lineaires/1.5-1.6. Matrices Echelonn\303\251es.ipynb" @@ -1,330 +1,298 @@ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Concept(s)-clé(s) et théorie\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ " \n", " " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import AL_Fct as al\n", "import numpy as np\n", "import ipywidgets as widgets\n", "import random\n", "\n", "from ipywidgets import interact, interactive, fixed, interact_manual" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### ** EXERCICE 1**\n", + "### **Exercice 1**\n", "\n", - "Trouver la solution du système en échelonnant la matrice augmentée correspondante\n", + "À l'aide des opérations élémentaires, échelonner et réduire les matrices ci-dessous.\n", "\n", "$$\n", - "\\begin{cases}\n", - "\\end{cases}\n", - "$$\n" + "\\begin{pmatrix}\n", + "2 & -1\\\\\n", + "1 &2\n", + "\\end{pmatrix}\\hskip2em\n", + "\\begin{pmatrix}\n", + "\\dfrac{1}{2} & 3 & 0\\\\\n", + "2 & -4 & 6\\\\\n", + "1 & 3 &-1\n", + "\\end{pmatrix}\\hskip2em\n", + "\\begin{pmatrix}\n", + "1 & 0 &1\\\\\n", + "0 & 1 & -1\\\\\n", + "1 & 1 &-1\n", + "\\end{pmatrix}\n", + "$$" ] }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "A=[[2,-1], [1,2]]" + ] + }, + { + "cell_type": "code", + "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Vous allez échelonner la matrice\n" ] }, { "data": { "text/latex": [ - "$\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\4 & 5 & 6 & 0 & 1 & 0 \\\\7 & 8 & 9 & 0 & 0 & 1 \\end{array}\\right)$" + "$\\left(\\begin{array}{cc} 2 & -1 \\\\1 & 2 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Régler les paramètres et évaluer la cellule suivante\n", "Répéter cela jusqu'à obtenir une forme échelonnée réduite\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "f04476e011d244709526299fba48dd5b", + "model_id": "8f22beb9f62f4cdba6fc3da82b889044", "version_major": 2, "version_minor": 0 }, "text/plain": [ "RadioButtons(description='Opération:', options=('Eij', 'Ei(alpha)', 'Eij(alpha)'), value='Eij')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "f1de3bef209141d5a8e554794000c35a", + "model_id": "bc00d64d4a154dbe824417f540e1063e", "version_major": 2, "version_minor": 0 }, "text/plain": [ - "BoundedIntText(value=1, description='Ligne i:', max=3, min=1)" + "BoundedIntText(value=1, description='Ligne i:', max=2, min=1)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "58c5123f244742bf8e73093c77f96d03", + "model_id": "200d9b1e0b9f45abb3f91b43bae2579d", "version_major": 2, "version_minor": 0 }, "text/plain": [ - "BoundedIntText(value=1, description='Ligne j:', max=3, min=1)" + "BoundedIntText(value=1, description='Ligne j:', max=2, min=1)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "0673c0ee0a394dbcb192a888ee4b6638", + "model_id": "4171b37c5ff94c4789b6f4d9b2a5329a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Text(value='1', description='Coeff. alpha:')" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ - "A=[[1,2,3],[4,5,6],[7,8,9]]\n", - "b=[[1,0,0],[0,1,0], [0,0,1]]\n", "print('Vous allez échelonner la matrice')\n", - "al.printAAug(A,b)\n", - "[i,j,r,alpha]= al.manualEch(A,b)\n", - "m=np.concatenate((A,b), axis=1)\n", + "al.printA(A)\n", + "[i,j,r,alpha]= al.manualEch(A)\n", "MatriceList=[A]\n", - "RhSList=[b]" + "m=np.matrix(A)" ] }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/latex": [ - "$\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\4 & 5 & 6 & 0 & 1 & 0 \\\\7 & 8 & 9 & 0 & 0 & 1 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\4 & 5 & 6 & 0 & 1 & 0 \\\\7 & 8 & 9 & 0 & 0 & 1 \\end{array}\\right)$" + "$\\left(\\begin{array}{cc} 2 & -1 \\\\1 & 2 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{cc} 2 & -1 \\\\1 & 2 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{cc} 1 & 2 \\\\2 & -1 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{cc} 1 & 2 \\\\2 & -1 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ - "if alpha.value==0:\n", - " print('Le coefficient alpha doit être non-nul!')\n", - "if r.value=='Eij':\n", - " m=al.Eij(m,i.value-1,j.value-1)\n", - "if r.value=='Ei(alpha)':\n", - " m=al.Ealpha(m,i.value-1,eval(alpha.value))\n", - "if r.value=='Eij(alpha)':\n", - " m=al.Eijalpha(m,i.value-1,j.value-1,eval(alpha.value))\n", - " \n", - "MatriceList.append(m[:,0:len(A[0])])\n", - "RhSList.append(m[:,len(A[0]):])\n", - "\n", - "al.printEquMatricesAug(MatriceList,RhSList)" + "al.echelonnage(i,j,r,alpha,A,m,MatriceList)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### ** VERIFICATION **\n", - "À l'aide des cellules ci-dessous, vous pouvez entrer la matrice (des coefficients ou augmentée) de votre choix et obtenir une forme échelonnée et sa forme échelonnée réduite." + "### **VERIFICATION**\n", + "À l'aide des cellules ci-dessous, vous pouvez entrer la matrice (des coefficients ou augmentée) de votre choix et obtenir une forme échelonnée et sa forme échelonnée réduite.\n", + "\n", + "Pour **les formes échelonnées** on utilise la syntaxe suivante\n", + "\n", + "1. Pour la matrice $A$ : al.echelonMat('E', A)\n", + "2. Pour la matrice augmentée $(A | b)$ : al.echelonMat('E', A, b)\n", + "\n", + "Pour obenir **les formes échelonnées réduites** mettez 'ER' au lieu de 'E'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "A=[[1,2,3,4], [5,6,7,8], [9,10,11,12]]\n", "b=[[-1],[-2],[-3]]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "La matrice est sous la forme échelonnée\n" ] }, { "data": { "text/latex": [ "$\\left(\\begin{array}{ccccc} 1 & 2 & 3 & 4 & -1 \\\\5 & 6 & 7 & 8 & -2 \\\\9 & 10 & 11 & 12 & -3 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccccc} 1 & 2 & 3 & 4 & -1 \\\\0 & 1 & 2 & 3 & -0.75 \\\\0 & 0 & 0 & 0 & 0 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "La matrice est sous la forme échelonnée réduite\n" ] }, { "data": { "text/latex": [ "$\\left(\\begin{array}{cccccc} 1 & 2 & 3 & 4 & -1 & -1 \\\\5 & 6 & 7 & 8 & -2 & -2 \\\\9 & 10 & 11 & 12 & -3 & -3 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccccc} 1 & 0 & -1 & -2 & 0.5 \\\\0 & 1 & 2 & 3 & -0.75 \\\\0 & 0 & 0 & 0 & 0 \\end{array}\\right)$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "M=al.echelonMat('ER',A,b)" ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import AL_Fct as al\n", - "import numpy as np\n", - "Mat=[[2,2],[-2,3], [1,0]]\n", - "b=[[3],[2],[1]]\n", - "\n", - "Mat=al.echelonMat(Mat, b) #attention différence entre ech [A | b] ou [A]\n", - "Mat=np.array(Mat)\n", - "print(Mat[3:len(Mat),:])\n", - "Mat[3:len(Mat),:]=0\n", - "print(len(Mat), len(Mat[1,:]))\n", - "i=(len(Mat)-1)\n", - "while i>=1:\n", - " print('i=',i)\n", - " while all(abs(Mat[i,:len(Mat[0])-1])<1e-15) and i!=0:#if ligne (or rest of) is zero, take next ligne\n", - " i-=1\n", - " print('here')\n", - " #we have a lign with one non-nul element\n", - " j=i #we can start at pos ij at least the pivot is there\n", - " if abs(Mat[i,j])<1e-15: #if element Aij=0 take next one --> find pivot\n", - " j+=1\n", - " #Aij!=0 and Aij==1 if echelonMat worked\n", - " print('i=',i,'j=',j, 'Mat(i,:)', Mat[i,:]) \n", - " for k in range(i): #put zeros above pivot (which is 1 now)\n", - " print('k=',k)\n", - " Mat=al.Eijalpha(Mat, k,i, -Mat[k,j])\n", - " i-=1\n", - " al.printA(Mat)\n", - "\n", - "print(\"La matrice est sous la forme échelonnée réduite\")\n", - "al.printEquMatrices([MatCoeff, Mat])\n" - ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 2 } diff --git "a/Chapitre 1 - Systemes equations lineaires/1.7. R\303\251solutions de syst\303\250mes lin\303\251aires.ipynb" "b/Chapitre 1 - Systemes equations lineaires/1.7. R\303\251solutions de syst\303\250mes lin\303\251aires.ipynb" new file mode 100644 index 0000000..833ca76 --- /dev/null +++ "b/Chapitre 1 - Systemes equations lineaires/1.7. R\303\251solutions de syst\303\250mes lin\303\251aires.ipynb" @@ -0,0 +1,92 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Concept(s)-clé(s) et théorie\n", + "\n", + "DÉFINITION 1 :\n", + "Soit $B$ une matrice échelonnée. Alors les inconnues (du système linéaire associé) dont la colonne correspondante ne possède pas de pivot sont appelées les inconnues libres. Les inconnues dont la colonne correspondante possède un pivot sont appelées les inconnues principales.\n", + "\n", + "MÉTHODE DE RÉSOLUTION DE SYSTÈMES LINÉAIRES :\n", + "Soit $S$ un système linéaire à $n$ inconnues. Afin de trouver l'ensemble des solutions de $S$, on procède comme suit :\n", + "\n", + "1. Poser A la matrice augmentée du système.\n", + "2. Utiliser la méthode d'élimination de Gauss afin de transformer A en une matrice échelonnée B.\n", + "3. Si la matrice B possède une ligne de la forme $(0\\, 0 \\,⋯ \\,0 \\,|\\, c )$ avec $c\\neq 0$, alors le système ne possède aucune solution.\n", + "4. S'il existe n pivots, aucun dans la dernière colonne, alors il existe une unique solution.\n", + "5. S'il existe moins de n pivots, aucun dans la dernière colonne, alors il existe un nombre infini de solutions.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### **EXERCICE 1**\n", + "\n", + "Trouver la solution du système en échelonnant la matrice augmentée correspondante\n", + "\n", + "$$\n", + "\\begin{cases}\n", + "-3x_1 + \\dfrac{1}{3}x_2 -x_3&=0\\\\\n", + "x_1 -4x_2 + x_3&=2\\\\\n", + "x_2 -5 x_3&=-2\n", + "\\end{cases}\n", + "$$\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "A=[[-2,2/3,-1],[1,-2,1],[0,1,-5]]\n", + "b=[[0],[2], [-3]]\n", + "print('Vous allez échelonner la matrice')\n", + "al.printAAug(A,b)\n", + "[i,j,r,alpha]= al.manualEch(A,b)\n", + "m=np.concatenate((A,b), axis=1)\n", + "MatriceList=[A]\n", + "RhSList=[b]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "al.echelonnage(i,j,r,alpha,m,MatriceList,RhSList)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Chapitre 1 - Systemes equations lineaires/AL_Fct.py b/Chapitre 1 - Systemes equations lineaires/AL_Fct.py index 9854864..958e183 100644 --- a/Chapitre 1 - Systemes equations lineaires/AL_Fct.py +++ b/Chapitre 1 - Systemes equations lineaires/AL_Fct.py @@ -1,671 +1,710 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 16:42:29 2019 @author: jecker """ from __future__ import division import numpy as np from IPython.display import display, Latex import matplotlib.pyplot as plt import math import plotly import plotly.plotly as py import plotly.graph_objs as go plotly.offline.init_notebook_mode(connected=True) from IPython.core.magic import register_cell_magic from IPython.display import HTML import ipywidgets as widgets import random from ipywidgets import interact, interactive, fixed, interact_manual @register_cell_magic def bgc(color, cell=None): script = ( "var cell = this.closest('.jp-CodeCell');" "var editor = cell.querySelector('.jp-Editor');" "editor.style.background='{}';" "this.parentNode.removeChild(this)" ).format(color) display(HTML(''.format(script))) ############################################################################### ## PRINTS Equations, systems, matrix def strEq(n,coeff):# Latex str of one equation in format a1x1+ ...+anxn or with coefficients. Eq='' if str(coeff)=='' or coeff==[]: if n==1: Eq=Eq + 'a_1x_1 = b' elif n==2: Eq=Eq + 'a_1x_1 + a_2x_2 = b' else: Eq=Eq + 'a_1x_1 + \ldots + ' + 'a_' + str(n) + 'x_'+ str(n) + '=b' else : if n==1: Eq=Eq + str(round(coeff[0],3) if coeff[0] % 1 else int(coeff[0]))+ 'x_'+str(1) +\ '='+ str(round(coeff[len(coeff)-1],3) if coeff[len(coeff)-1] % 1 else int(coeff[len(coeff)-1])) else: Eq=Eq + str(round(coeff[0],3) if coeff[0] % 1 else int(coeff[0]))+ 'x_'+str(1) for i in range(1,n-1): Eq=Eq + ' + ' + str(round(coeff[i],3) if coeff[i] %1 else int(coeff[i])) + 'x_' + str(i+1) Eq=Eq + ' + ' +str(round(coeff[len(coeff)-2],3) if coeff[len(coeff)-2] % 1 else int(coeff[len(coeff)-2]))\ + 'x_' + str(n) + '=' + str(round(coeff[len(coeff)-1],3) if coeff[len(coeff)-1] % 1 else int(coeff[len(coeff)-1])) return Eq def printEq(coeff,b, *args):# Latex Print of one equation in format a1x1+ ...+anxn or with coefficients. if len(args)==1: n=args[0] else: n=len(coeff) coeff=coeff+b texEq='$' texEq=texEq+ strEq(n,coeff) texEq=texEq + '$' display(Latex(texEq)) def printSyst(A,b, *args):# Latex Print of one system of m equation in format ai1x1+ ...+ainxn=bi or with coeff in MatCoeff. if (len(args)==2) or (len(A)==len(b)): #ensures that MatCoeff has proper dimensions if len(args)==2: m=args[0] n=args[1] else: m=len(A) n=len(A[0]) texSyst='$\\begin{cases}' Eq_list=[] if type(b[0])==list: b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) else: A = [A[i]+[b[i]]for i in range(0,m)] #becomes augmented matrix A=np.array(A) #just in case it's not for i in range(m): if str(A)=='': Eq_i='' if n==1: Eq_i=Eq_i + 'a_{' + str(i+1) + '1}' + 'x_1 = b_' + str(i+1) elif n==2: Eq_i=Eq_i + 'a_{' + str(i+1) + '1}' + 'x_1 + ' + 'a_{' + str(i+1) + '2}' + 'x_2 = b_' + str(i+1) else: Eq_i=Eq_i + 'a_{' + str(i+1) + '1}' + 'x_1 + \ldots +' + 'a_{' + str(i+1) +str(n) + '}' + 'x_'+ str(n) + '=b_' + str(i+1) else: Eq_i=strEq(n,A[i,:]) #attention A is (A|b) Eq_list.append(Eq_i) texSyst=texSyst+ Eq_list[i] + '\\\\' texSyst =texSyst+ '\\end{cases}$' display(Latex(texSyst)) else: print("La matrice des coefficients n'a pas les bonnes dimensions") def texMatrix(*args): #return tex expression of one matrix of A or (A|b) -- or (A|B) VERIFIED OK if len(args)==2: # matrice augmentée A=np.matrix(args[0]).astype(float) m=A.shape[0] b=args[1] #b=[b[i] for i in range(m)] b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) texApre ='\\left(\\begin{array}{' texA = '' for i in np.asarray(A) : texALigne = '' texALigne = texALigne + str(round(i[0],3) if i[0] %1 else int(i[0])) if texA == '' : texApre = texApre + 'c' for j in i[1:m] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) if texA == '' : texApre = texApre + '| c' for j in i[m:] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) texALigne = texALigne + ' \\\\' texA = texA + texALigne texA = texApre + '} ' + texA[:-2] + ' \\end{array}\\right)' elif len(args)==1: #matrice des coefficients A=np.matrix(args[0]).astype(float) texApre ='\\left(\\begin{array}{' texA = '' for i in np.asarray(A) : texALigne = '' texALigne = texALigne + str(round(i[0],3) if i[0] %1 else int(i[0])) if texA == '' : texApre = texApre + 'c' for j in i[1:] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) texALigne = texALigne + ' \\\\' texA = texA + texALigne texA = texApre + '} ' + texA[:-2] + ' \\end{array}\\right)' else: print("Ce n'est pas une matrice des coefficients ni une matrice augmentée") return texA def printA(*args) : #Print matrix VERIFIED OK texA='$'+ texMatrix(*args) + '$' # print(texA) display(Latex(texA)) -def printEquMatrices(*args): # M=[M1, M2, ..., Mn] n>1 VERIFIED OK - texEqu='$' + texMatrix(args[0]) - for i in range(1,len(args)): - texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(args[i]) - texEqu=texEqu+ '$' - display(Latex(texEqu)) + +def printEquMatrices(*args): #list of matrices is M=[M1, M2, ..., Mn] where Mi=(Mi|b) + if len(args)==2: + listOfMatrices=args[0] + listOfRhS=args[1] + texEqu='$' + texMatrix(listOfMatrices[0],listOfRhS[0]) + for i in range(1,len(listOfMatrices)): + texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(listOfMatrices[i], listOfRhS[i]) + texEqu=texEqu+ '$' + display(Latex(texEqu)) + else: + listOfMatrices=args[0] + texEqu='$' + texMatrix(listOfMatrices[0]) + for i in range(1,len(listOfMatrices)): + texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(listOfMatrices[i]) + texEqu=texEqu+ '$' + display(Latex(texEqu)) - -def printEquMatricesAug(listOfMatrices, listOfRhS): #list of matrices is M=[M1, M2, ..., Mn] where Mi=(Mi|b) - texEqu='$' + texMatrixAug(listOfMatrices[0],listOfRhS[0]) - for i in range(1,len(listOfMatrices)): - texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrixAug(listOfMatrices[i], listOfRhS[i]) - texEqu=texEqu+ '$' - display(Latex(texEqu)) #%% Functions to enter smth def EnterInt(n): #function enter integer. while type(n)!=int: try: n=int(n) if n<=0: print("Le nombre ne peut pas être négatif!") print("Entrez à nouveau : ") n=input() except: print("Ce n'est pas un entier!") print("Entrez à nouveau :") n=input() n=int(n) return n def EnterListReal(n): #function enter list of real numbers. coeff=input() while type(coeff)!=list: try: coeff=[float(eval(x)) for x in coeff.split(',')] if len(coeff)!=n+1: print("Vous n'avez pas entré le bon nombre de réels!") print("Entrez à nouveau : ") coeff=input() except: print("Ce n'est pas le bon format!") print("Entrez à nouveau") coeff=input() #coeff[abs(coeff)<1e-15]=0 #ensures that 0 is 0. return coeff #%%Verify if sol is the solution of the equation with coefficients coeff def SolOfEq(sol,coeff, i): A = np.asarray(coeff[0:len(coeff)-1]) if abs(np.dot(A,sol)-coeff[len(coeff)-1])<1e-10: print("La suite entrée est une solution de l'équation", i) else: print("La suite entrée n'est pas une solution de l'équation",i) return abs(np.dot(A,sol)-coeff[len(coeff)-1])<1e-10 def SolOfSyst(solution,A,b): A = [A[i]+[b[i]] for i in range(0,len(A))] A=np.array(A) isSol=[SolOfEq(solution, A[i,:],i+1) for i in range(0,len(A))] if all(isSol[i]==True for i in range(len(isSol))): print("C'est une solution du système") else: print("Ce n'est pas une solution du système") #%%Plots using plotly def Plot2DSys(xL,xR,p,A,b): # small values for p allows for dots to be seen A = [A[i]+[b[i]] for i in range(0,len(A))] A=np.array(A) t=np.linspace(xL,xR,p) legend=[] data=[] for i in range(1,len(A)+1): if (abs(A[i-1,1])) > abs (A[i-1,0]) : #p0=[0,A[i-1,2]/A[i-1,1]] #p1=[1,(A[i-1,2]-A[i-1,0])/A[i-1,1]] trace=go.Scatter(x=t, y= (A[i-1,2]-A[i-1,0]*t)/A[i-1,1], name='Droite %d'%i) else : trace=go.Scatter(x=(A[i-1,2]-A[i-1,1]*t)/A[i-1,0], y= t, name='Droite %d'%i) data.append(trace) fig = go.Figure(data=data) plotly.offline.iplot(fig) def Plot3DSys(xL,xR,p,A,b): # small values for p allows for dots to be seen A = [A[i]+[b[i]] for i in range(0,len(A))] A=np.array(A) gr='rgb(102,255,102)' org='rgb(255,117,26)' red= 'rgb(255,0,0)' blue='rgb(51, 214, 255)' colors =[blue, gr, org] s = np.linspace(xL, xR ,p) t = np.linspace(xL, xR, p) tGrid, sGrid = np.meshgrid(s, t) data=[] for i in range(0, len(A)): colorscale=[[0.0,colors[i]], [0.1, colors[i]], [0.2, colors[i]], [0.3, colors[i]], [0.4, colors[i]], [0.5, colors[i]], [0.6, colors[i]], [0.7, colors[i]], [0.8, colors[i]], [0.9, colors[i]], [1.0, colors[i]]] j=i+1 if (abs(A[i,2])) > abs (A[i,1]) : # z en fonction de x,y x = sGrid y = tGrid surface = go.Surface(x=x, y=y, z=(A[i,3]-A[i,0]*x -A[i,1]*y)/A[i,2], showscale=False, colorscale=colorscale, opacity=1, name='Plan %d' %j) elif (A[i,2]==0 and A[i,1]==0): # x =b y = sGrid z = tGrid surface = go.Surface(x=A[i,3]-A[i,1]*y, y=y, z=z, showscale=False, colorscale=colorscale, opacity=1, name='Plan %d' %j) else:# y en fonction de x,z x = sGrid z = tGrid surface = go.Surface(x=x, y=(A[i,3]-A[i,0]*x -A[i,2]*z)/A[i,1], z=z, showscale=False, colorscale=colorscale, opacity=1, name='Plan %d' %j) data.append(surface) layout = go.Layout( showlegend=True, #not there WHY???? legend=dict(orientation="h"), autosize=True, width=800, height=800, scene=go.Scene( xaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), yaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), zaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ) ) ) fig = go.Figure(data=data, layout=layout) plotly.offline.iplot(fig) #%%Echelonnage def echZero(indice, M): #echelonne la matrice pour mettre les zeros dans les lignes du bas. M (matrice ou array) et Mat (list) pas le même format. Mat=M[indice==False,:].ravel() Mat=np.concatenate([Mat,M[indice==True,:].ravel()]) Mat=Mat.reshape(len(M), len(M[0,:])) return Mat def Eij(M, i,j): #matrice elementaire, echange la ligne i avec la ligne j M=np.array(M) M[[i,j],:]=M[[j,i],:] return M def Ealpha(M, i, alpha): # matrice elementaire, multiple la ligne i par le scalaire alpha M=np.array(M) M[i,:]=alpha*M[i,:] return M def Eijalpha(M, i,j, alpha): # matrice elementaire, AJOUTE à la ligne i alpha *ligne j. Attention alpha + ou - M=np.array(M) M[i,:]=M[i,:] + alpha *M[j,:] return M def echelonMat(ech,*args): #Nous donne la matrice echelonnée 'E' ou reduite 'ER' d'une matrice des coeffs. ou augmentée. if len(args)==2: # matrice augmentée A=np.matrix(args[0]).astype(float) m=A.shape[0] b=args[1] if type(b[0])==list: b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) else: b=[b[i] for i in range(m)] A = [A[i]+[b[i]]for i in range(0,m)] else: # matrice coeff A=np.matrix(args[0]).astype(float) m=A.shape[0] b=np.zeros(m) A=np.concatenate((A,b), axis=1) if ech=='E': #Echelonnée Mat=np.array(A) Mat=Mat.astype(float) # in case the array in int instead of float. numPivot=0 for i in range(len(Mat)): j=i while all(abs(Mat[j:,i])<1e-15) and j!=len(Mat[0,:])-1: #if column (or rest of) is 0, take next j+=1 if j==len(Mat[0,:])-1: if len(Mat[0,:])>j: Mat[i+1:len(Mat),:]=0 print("La matrice est sous la forme échelonnée") printEquMatrices(np.asmatrix(A), np.asmatrix(Mat)) break if abs(Mat[i,j])<1e-15: Mat[i,j]=0 zero=abs(Mat[i:,j])<1e-15 M= echZero(zero,Mat[i:,:] ) Mat[i:,:]=M Mat=Ealpha(Mat, i,1/Mat[i,j] ) #normalement Mat[i,j]!=0 for k in range(i+1,len(A)): Mat=Eijalpha(Mat, k,i, -Mat[k,j]) #Mat[k,:]=[0 if abs(Mat[k,l])<1e-15 else Mat[k,l] for l in range(len(MatCoeff[0,:]))] numPivot+=1 Mat[abs(Mat)<1e-15]=0 #printA(np.array(Mat)) elif ech=='ER': # Echelonnée réduite Mat=np.array(A) Mat=Mat.astype(float) # in case the array in int instead of float. numPivot=0 for i in range(len(Mat)): j=i while all(abs(Mat[j:,i])<1e-15) and j!=len(Mat[0,:])-1: #if column (or rest of) is zero, take next column j+=1 if j==len(Mat[0,:])-1: #ADD ZERO LINES BELOW!!!!!! if len(Mat[0,:])>j: Mat[i+1:len(Mat),:]=0 print("La matrice est sous la forme échelonnée") printEquMatrices(np.asmatrix(A), np.asmatrix(Mat)) break if abs(Mat[i,j])<1e-15: Mat[i,j]=0 zero=abs(Mat[i:,j])<1e-15 M= echZero(zero,Mat[i:,:] ) Mat[i:,:]=M Mat=Ealpha(Mat, i,1/Mat[i,j] ) #normalement Mat[i,j]!=0 for k in range(i+1,len(A)): Mat=Eijalpha(Mat, k,i, -Mat[k,j]) #Mat[k,:]=[0 if abs(Mat[k,l])<1e-15 else Mat[k,l] for l in range(len(MatCoeff[0,:]))] numPivot+=1 Mat[abs(Mat)<1e-15]=0 Mat=np.array(Mat) MatAugm=np.concatenate((A,b), axis=1) # MatAugm = [A[i]+[b[i]] for i in range(0,len(A))] i=(len(Mat)-1) while i>=1: while all(abs(Mat[i,:len(Mat[0])-1])<1e-15) and i!=0:#if ligne (or rest of) is zero, take next ligne i-=1 #we have a lign with one non-nul element j=i #we can start at pos ij at least the pivot is there if abs(Mat[i,j])<1e-15: #if element Aij=0 take next one --> find pivot j+=1 #Aij!=0 and Aij==1 if echelonMat worked for k in range(i): #put zeros above pivot (which is 1 now) Mat=Eijalpha(Mat, k,i, -Mat[k,j]) i-=1 #printA(Mat) print("La matrice est sous la forme échelonnée réduite") printEquMatrices(MatAugm, Mat) return np.asmatrix(Mat) -def echelonMatCoeff(A): #take echelonMAt but without b. - b= [0 for i in range(len(A))] - Mat = [A[i]+[b[i]] for i in range(0,len(A))] - Mat=np.array(Mat) - Mat=Mat.astype(float) # in case the array in int instead of float. - numPivot=0 - for i in range(len(Mat)): - j=i - while all(abs(Mat[j:,i])<1e-15) and j!=len(Mat[0,:])-1: #if column (or rest of) is zero, take next column - j+=1 - if j==len(Mat[0,:])-1: - #ADD ZERO LINES BELOW!!!!!! - if len(Mat[0,:])>j: - Mat[i+1:len(Mat),:]=0 - print("La matrice est sous la forme échelonnée") - printEquMatrices(np.asmatrix(A), np.asmatrix(Mat[:, :len(A[0])])) - break - if abs(Mat[i,j])<1e-15: - Mat[i,j]=0 - zero=abs(Mat[i:,j])<1e-15 - M= echZero(zero,Mat[i:,:] ) - Mat[i:,:]=M - Mat=Ealpha(Mat, i,1/Mat[i,j] ) #normalement Mat[i,j]!=0 - for k in range(i+1,len(A)): - Mat=Eijalpha(Mat, k,i, -Mat[k,j]) - #Mat[k,:]=[0 if abs(Mat[k,l])<1e-15 else Mat[k,l] for l in range(len(MatCoeff[0,:]))] - numPivot+=1 - Mat[abs(Mat)<1e-15]=0 - #printA(np.asmatrix(Mat[:, :len(A[0])])) - return np.asmatrix(Mat) - -def echelonRedMat(A, b): - Mat=echelonMat('ER',A,b) - Mat=np.array(Mat) - MatAugm=np.concatenate((A,b), axis=1) - # MatAugm = [A[i]+[b[i]] for i in range(0,len(A))] - i=(len(Mat)-1) - while i>=1: - while all(abs(Mat[i,:len(Mat[0])-1])<1e-15) and i!=0:#if ligne (or rest of) is zero, take next ligne - i-=1 - #we have a lign with one non-nul element - j=i #we can start at pos ij at least the pivot is there - if abs(Mat[i,j])<1e-15: #if element Aij=0 take next one --> find pivot - j+=1 - #Aij!=0 and Aij==1 if echelonMat worked - for k in range(i): #put zeros above pivot (which is 1 now) - Mat=Eijalpha(Mat, k,i, -Mat[k,j]) - i-=1 - printA(Mat) - print("La matrice est sous la forme échelonnée réduite") - printEquMatrices(MatAugm, Mat) - return np.asmatrix(Mat) #Generate random matrix def randomA(): n=random.randint(1,10) m=random.randint(1,10) A=np.empty([m,n],dtype=int) A=[[random.randint(-100,100) for i in range(n)] for j in range(m)] printA(A) return np.matrix(A) def dimensionA(A): m=widgets.IntText( value=1, step=1, description='m:', disabled=False ) n=widgets.IntText( value=1, step=1, - description='n:', + description='m:', disabled=False ) display(m) display(n) def f(): if m.value==A.shape[0] and n.value==A.shape[1]: print('Correcte!') else: print('Incorrecte, entrez de nouvelles valeurs') out=interact_manual(f) def manualEch(*args): if len(args)==2: # matrice augmentée A=np.matrix(args[0]).astype(float) m=A.shape[0] b=args[1] #b=[b[i] for i in range(m)] if type(b[0])==list: b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) else: b=[b[i] for i in range(m)] A = [A[i]+[b[i]]for i in range(0,m)] else: A=np.matrix(args[0]).astype(float) m=A.shape[0] A=np.array(A) #just in case it's not j=widgets.BoundedIntText( value=1, min=1, max=m, step=1, description='Ligne j:', disabled=False ) i=widgets.BoundedIntText( value=1, min=1, max=m, step=1, description='Ligne i:', disabled=False ) r=widgets.RadioButtons( options=['Eij', 'Ei(alpha)', 'Eij(alpha)'], description='Opération:', disabled=False ) alpha=widgets.Text( value='1', description='Coeff. alpha:', disabled=False ) print("Régler les paramètres et évaluer la cellule suivante") print("Répéter cela jusqu'à obtenir une forme échelonnée réduite") display(r) display(i) display(j) display(alpha) return i,j,r,alpha +def echelonnage(i,j,r,alpha,A,m,*args): #1.5-1.6 Matrice echelonnées + if alpha.value==0: + print('Le coefficient alpha doit être non-nul!') + if r.value=='Eij': + m=Eij(m,i.value-1,j.value-1) + if r.value=='Ei(alpha)': + m=Ealpha(m,i.value-1,eval(alpha.value)) + if r.value=='Eij(alpha)': + m=Eijalpha(m,i.value-1,j.value-1,eval(alpha.value)) + if len(args)==2: + MatriceList=args[0] + RhSList=args[1] + MatriceList.append(m[:,0:len(A[0])]) + printEquMatrices(MatriceList,RhSList) + else: + MatriceList=args[0] + MatriceList.append(m[:,0:len(A[0])]) + printEquMatrices(MatriceList) + + def manualOp(*args): if len(args)==2: # matrice augmentée A=np.matrix(args[0]).astype(float) m=A.shape[0] b=args[1] #b=[b[i] for i in range(m)] if type(b[0])==list: b=np.matrix(b).astype(float) A=np.concatenate((A,b), axis=1) else: b=[b[i] for i in range(m)] A = [A[i]+[b[i]]for i in range(0,m)] else: A=np.matrix(args[0]).astype(float) m=A.shape[0] A=np.array(A) #just in case it's not j=widgets.BoundedIntText( value=1, min=1, max=m, step=1, description='Ligne j:', disabled=False ) i=widgets.BoundedIntText( value=1, min=1, max=m, step=1, description='Ligne i:', disabled=False ) r=widgets.RadioButtons( options=['Eij', 'Ei(alpha)', 'Eij(alpha)'], description='Opération:', disabled=False ) alpha=widgets.Text( value='1', description='Coeff. alpha:', disabled=False ) print("Régler les paramètres et cliquer sur RUN INTERACT pour effectuer votre opération") def f(r,i,j,alpha): m=np.concatenate((A,b), axis=1) MatriceList=[A] RhSList=[b] if alpha==0: print('Le coefficient alpha doit être non-nul!') if r=='Eij': m=Eij(m,i-1,j-1) if r=='Ei(alpha)': m=Ealpha(m,i.value-1,eval(alpha)) if r=='Eij(alpha)': m=Eijalpha(m,i-1,j-1,eval(alpha)) MatriceList.append(m[:,0:len(A[0])]) RhSList.append(m[:,len(A[0]):]) printEquMatricesAug(MatriceList,RhSList) interact_manual(f,r=r,i=i,j=j,alpha=alpha) -#OBSOLETE +########################################OBSOLETE +def printEquMatricesAug(listOfMatrices, listOfRhS): #list of matrices is M=[M1, M2, ..., Mn] where Mi=(Mi|b) + texEqu='$' + texMatrixAug(listOfMatrices[0],listOfRhS[0]) + for i in range(1,len(listOfMatrices)): + texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrixAug(listOfMatrices[i], listOfRhS[i]) + texEqu=texEqu+ '$' + display(Latex(texEqu)) + +def echelonMatCoeff(A): #take echelonMAt but without b. + b= [0 for i in range(len(A))] + Mat = [A[i]+[b[i]] for i in range(0,len(A))] + Mat=np.array(Mat) + Mat=Mat.astype(float) # in case the array in int instead of float. + numPivot=0 + for i in range(len(Mat)): + j=i + while all(abs(Mat[j:,i])<1e-15) and j!=len(Mat[0,:])-1: #if column (or rest of) is zero, take next column + j+=1 + if j==len(Mat[0,:])-1: + #ADD ZERO LINES BELOW!!!!!! + if len(Mat[0,:])>j: + Mat[i+1:len(Mat),:]=0 + print("La matrice est sous la forme échelonnée") + printEquMatrices(np.asmatrix(A), np.asmatrix(Mat[:, :len(A[0])])) + break + if abs(Mat[i,j])<1e-15: + Mat[i,j]=0 + zero=abs(Mat[i:,j])<1e-15 + M= echZero(zero,Mat[i:,:] ) + Mat[i:,:]=M + Mat=Ealpha(Mat, i,1/Mat[i,j] ) #normalement Mat[i,j]!=0 + for k in range(i+1,len(A)): + Mat=Eijalpha(Mat, k,i, -Mat[k,j]) + #Mat[k,:]=[0 if abs(Mat[k,l])<1e-15 else Mat[k,l] for l in range(len(MatCoeff[0,:]))] + numPivot+=1 + Mat[abs(Mat)<1e-15]=0 + #printA(np.asmatrix(Mat[:, :len(A[0])])) + return np.asmatrix(Mat) + +def echelonRedMat(A, b): + Mat=echelonMat('ER',A,b) + Mat=np.array(Mat) + MatAugm=np.concatenate((A,b), axis=1) + # MatAugm = [A[i]+[b[i]] for i in range(0,len(A))] + i=(len(Mat)-1) + while i>=1: + while all(abs(Mat[i,:len(Mat[0])-1])<1e-15) and i!=0:#if ligne (or rest of) is zero, take next ligne + i-=1 + #we have a lign with one non-nul element + j=i #we can start at pos ij at least the pivot is there + if abs(Mat[i,j])<1e-15: #if element Aij=0 take next one --> find pivot + j+=1 + #Aij!=0 and Aij==1 if echelonMat worked + for k in range(i): #put zeros above pivot (which is 1 now) + Mat=Eijalpha(Mat, k,i, -Mat[k,j]) + i-=1 + printA(Mat) + print("La matrice est sous la forme échelonnée réduite") + printEquMatrices(MatAugm, Mat) + return np.asmatrix(Mat) + def printEquMatricesOLD(listOfMatrices): #list of matrices is M=[M1, M2, ..., Mn] texEqu='$' + texMatrix(listOfMatrices[0]) for i in range(1,len(listOfMatrices)): texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(listOfMatrices[i]) texEqu=texEqu+ '$' display(Latex(texEqu)) def texMatrixAug(A,b): #return tex expression of one matrix (A|b) where b can also be a matrix m=len(A[0]) A=np.concatenate((A,b), axis=1) texApre ='\\left(\\begin{array}{' texA = '' for i in np.asarray(A) : texALigne = '' texALigne = texALigne + str(round(i[0],3) if i[0] %1 else int(i[0])) if texA == '' : texApre = texApre + 'c' for j in i[1:m] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) if texA == '' : texApre = texApre + '| c' for j in i[m:] : if texA == '' : texApre = texApre + 'c' texALigne = texALigne + ' & ' + str(round(j,3) if j %1 else int(j)) texALigne = texALigne + ' \\\\' texA = texA + texALigne texA = texApre + '} ' + texA[:-2] + ' \\end{array}\\right)' return texA def printAAug(A,b) : #Print matrix (A|b) texA='$'+ texMatrixAug(A,b) + '$' # print(texA) display(Latex(texA)) - \ No newline at end of file + + +def printEquMatricesOLD(*args): # M=[M1, M2, ..., Mn] n>1 VERIFIED OK + texEqu='$' + texMatrix(args[0]) + for i in range(1,len(args)): + texEqu=texEqu+ '\\quad \\sim \\quad' + texMatrix(args[i]) + texEqu=texEqu+ '$' + display(Latex(texEqu)) \ No newline at end of file diff --git a/Chapitre 1 - Systemes equations lineaires/__pycache__/AL_Fct.cpython-36.pyc b/Chapitre 1 - Systemes equations lineaires/__pycache__/AL_Fct.cpython-36.pyc index ca0ada7..df2a57e 100644 Binary files a/Chapitre 1 - Systemes equations lineaires/__pycache__/AL_Fct.cpython-36.pyc and b/Chapitre 1 - Systemes equations lineaires/__pycache__/AL_Fct.cpython-36.pyc differ