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 9587207..9889ab2 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,301 +1,401 @@ #!/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, display @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 - -#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(n,coeff,b):# Latex Print of one equation in format a1x1+ ...+anxn or with coefficients. coeff=coeff+b texEq='$' texEq=texEq+ strEq(n,coeff) texEq=texEq + '$' display(Latex(texEq)) -def printSyst(m,n,MatCoeff,b):# Latex Print of one system of m equation in format ai1x1+ ...+ainxn=bi or with coeff in MatCoeff. - if (str(MatCoeff)=='') or (len(MatCoeff[1])==n and len(MatCoeff)==m): #ensures that MatCoeff has proper dimensions +def printSyst(m,n,A,b):# Latex Print of one system of m equation in format ai1x1+ ...+ainxn=bi or with coeff in MatCoeff. + if (str(A)=='') or (len(A[1])==n and len(A)==m): #ensures that MatCoeff has proper dimensions texSyst='$\\begin{cases}' Eq_list=[] - MatCoeff = [MatCoeff[i]+[b[i]]for i in range(0,m)] - MatCoeff=np.array(MatCoeff) #just in case it's not + 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(MatCoeff)=='': + 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,MatCoeff[i,:]) + Eq_i=strEq(n,A[i,:]) 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(A): #return tex expression of one matrix +def texMatrix(A): #return tex expression of one matrix of coefficients + 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)' return texA + +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 printA(A) : #Print matrix texA='$'+ texMatrix(A) + '$' # print(texA) display(Latex(texA)) + + +def printAAug(A,b) : #Print matrix (A|b) + texA='$'+ texMatrixAug(A,b) + '$' + # print(texA) + display(Latex(texA)) def printEquMatrices(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 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,MatriceCoeff,b): - MatriceCoeff = [MatriceCoeff[i]+[b[i]] for i in range(0,len(MatriceCoeff))] - MatriceCoeff=np.array(MatriceCoeff) - isSol=[SolOfEq(solution, MatriceCoeff[i,:],i+1) for i in range(0,len(MatriceCoeff))] +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,MatCoeff,b): # small values for p allows for dots to be seen - MatCoeff = [MatCoeff[i]+[b[i]] for i in range(0,len(MatCoeff))] - MatCoeff=np.array(MatCoeff) +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(MatCoeff)+1): - if (abs(MatCoeff[i-1,1])) > abs (MatCoeff[i-1,0]) : - trace=go.Scatter(x=t, y= (MatCoeff[i-1,2]-MatCoeff[i-1,0]*t)/MatCoeff[i-1,1], name='Droite %d'%i) + for i in range(1,len(A)+1): + if (abs(A[i-1,1])) > abs (A[i-1,0]) : + 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=(MatCoeff[i-1,2]-MatCoeff[i-1,1]*t)/MatCoeff[i-1,0], y= t, name='Droite %d'%i) + 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,MatCoeff,b): # small values for p allows for dots to be seen - MatCoeff = [MatCoeff[i]+[b[i]] for i in range(0,len(MatCoeff))] - MatCoeff=np.array(MatCoeff) + + +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(MatCoeff)): + 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(MatCoeff[i,2])) > abs (MatCoeff[i,1]) : # z en fonction de x,y + 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=(MatCoeff[i,3]-MatCoeff[i,0]*x -MatCoeff[i,1]*y)/MatCoeff[i,2], + 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 (MatCoeff[i,2]==0 and MatCoeff[i,1]==0): # x =b + elif (A[i,2]==0 and A[i,1]==0): # x =b y = sGrid z = tGrid - surface = go.Surface(x=MatCoeff[i,3]-MatCoeff[i,1]*y, y=y, z=z, + 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=(MatCoeff[i,3]-MatCoeff[i,0]*x -MatCoeff[i,2]*z)/MatCoeff[i,1], z=z, + 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(MatCoeff): - Mat=np.array(MatCoeff) +def echelonMat(A,b): #Nous donne la matrice echelonne d un system [A|b] + A = [A[i]+[b[i]] for i in range(0,len(A))] + 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([A, 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)) + 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([MatCoeff, Mat]) + 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,i]!=0 - for k in range(i+1,len(MatCoeff)): + 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)) + printA(np.asmatrix(Mat[:, :len(A[0])])) + return np.asmatrix(Mat) + +def echelonRedMat(A, b): + Mat=echelonMat(A,b) + Mat=np.array(Mat) + 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 Mat diff --git a/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/Untitled-checkpoint.ipynb b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/Untitled-checkpoint.ipynb new file mode 100644 index 0000000..0671d6b --- /dev/null +++ b/Chapitre 1 - Systemes equations lineaires/.ipynb_checkpoints/Untitled-checkpoint.ipynb @@ -0,0 +1,390 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1. 2.]\n", + " [2. 3.]] [[1. 2.]\n", + " [2. 3.]]\n" + ] + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "c9e86c5fb43846df99ca8fdf750cdc63", + "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" + }, + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import ipywidgets as widgets\n", + "import numpy as np\n", + "from ipywidgets import interact, interactive, fixed, interact_manual\n", + "import AL_Fct as al\n", + "\n", + "r=widgets.RadioButtons(\n", + " options=['Eij', 'Ei(alpha)', 'Eij(alpha)'],\n", + "# value='pineapple',\n", + " description='Opération:',\n", + " disabled=False\n", + ")\n", + "\n", + "\n", + "alpha=widgets.Text(\n", + " value='1',\n", + " description='Coeff. alpha:',\n", + " disabled=False\n", + ")\n", + "\n", + "Matrice=[[1,2],[2,3]]\n", + "\n", + "Matrice=np.array(Matrice)\n", + "Matrice=Matrice.astype(float)\n", + "\n", + "i=widgets.BoundedIntText(\n", + " value=1,\n", + " min=0,\n", + " max=len(Matrice),\n", + " step=1,\n", + " description='Ligne i:',\n", + " disabled=False\n", + ")\n", + "\n", + "j=widgets.BoundedIntText(\n", + " value=1,\n", + " min=0,\n", + " max=len(Matrice),\n", + " step=1,\n", + " description='Ligne j:',\n", + " disabled=False\n", + ")\n", + "a= 1;\n", + "a=np.copy(Matrice)\n", + "print(a, Matrice)\n", + "def f(w1,w2,w3,w4,w5):\n", + " i,j=al.python2matlab(w2,w3)\n", + " print(a, Matrice)\n", + " w4=eval(w4)\n", + " if w4==0:\n", + " print('Le coefficient alpha doit être non-nul!')\n", + " return\n", + " if w1=='Eij':\n", + " w5=al.Eij(w5,i,j)\n", + " al.printEquMatrices([Matrice,w5,a])\n", + " print('Opération élémentaire', w1, 'échange la ligne', w2,' avec la ligne ',w3)\n", + " if w1=='Ei(alpha)':\n", + " w5=al.Ealpha(w5,i,w4)\n", + " al.printEquMatrices([Matrice2,w5])\n", + " print('Opération élémentaire', w1, 'multiplie la ligne', w3,' par',w4 )\n", + " if w1=='Eij(alpha)':\n", + " w5=al.Eijalpha(w5,i,j,w4)\n", + " al.printEquMatrices([Matrice2,w5])\n", + " print('Opération élémentaire', w1, 'additionne', w4,' fois la ligne ',w3, 'à la ligne',w2 )\n", + "\n", + "\n", + "interact_manual(f, w1=r, w2=i,w3=j,w4=alpha, w5=fixed(Matrice))\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + " \n", + " " + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "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)$" + ], + "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": "ffa237dcc53a44e69c419cc30b85bac7", + "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": "a84dbe9418a3492e9f4b0466f47109be", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "BoundedIntText(value=1, description='Ligne i:', max=3, min=1)" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "a835cbe7b129415992eb970b936e2417", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "BoundedIntText(value=1, description='Ligne j:', max=3, min=1)" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "733040b9c4b546bb8501b64e5639b2ba", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Text(value='1', description='Coeff. alpha:')" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "\n", + "import ipywidgets as widgets\n", + "import numpy as np\n", + "from ipywidgets import interact, interactive, fixed, interact_manual\n", + "import AL_Fct as al\n", + "Matrice=[[1,2,3],[4,5,6],[7,8,9]]\n", + "b=[[1,0,0],[0,1,0], [0,0,1]]\n", + "\n", + "Matrice=np.array(Matrice).astype(float)\n", + "b=np.array(b).astype(float)\n", + "\n", + "\n", + "print('Vous allez échelonner la matrice')\n", + "al.printAAug(Matrice,b)\n", + "j=widgets.BoundedIntText(\n", + " value=1,\n", + " min=1,\n", + " max=len(Matrice),\n", + " step=1,\n", + " description='Ligne j:',\n", + " disabled=False\n", + ")\n", + "i=widgets.BoundedIntText(\n", + " value=1,\n", + " min=1,\n", + " max=len(Matrice),\n", + " step=1,\n", + " description='Ligne i:',\n", + " disabled=False\n", + ")\n", + "\n", + "r=widgets.RadioButtons(\n", + " options=['Eij', 'Ei(alpha)', 'Eij(alpha)'],\n", + " description='Opération:',\n", + " disabled=False\n", + ")\n", + "\n", + "\n", + "alpha=widgets.Text(\n", + " value='1',\n", + " description='Coeff. alpha:',\n", + " disabled=False\n", + ")\n", + "\n", + "print(\"Régler les paramètres et évaluer la cellule suivante\")\n", + "print(\"Répéter cela jusqu'à obtenir une forme échelonnée réduite\")\n", + "display(r)\n", + "display(i)\n", + "display(j)\n", + "display(alpha)\n", + "\n", + "\n", + "m=np.concatenate((Matrice,b), axis=1)\n", + "\n", + "MatriceList=[Matrice]\n", + "RhSList=[b]\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[4 5 6]\n", + " [1 2 3]\n", + " [7 8 9]]\n", + "[[0 1 0]\n", + " [1 0 0]\n", + " [0 0 1]]\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)\\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)\\quad \\sim \\quad\\left(\\begin{array}{ccc| cccc} 4 & 5 & 6 & 0 & 1 & 0 \\\\1 & 2 & 3 & 1 & 0 & 0 \\\\7 & 8 & 9 & 0 & 0 & 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,alpha.value)\n", + " \n", + "MatriceList.append(m[:,0:len(Matrice[0])])\n", + "RhSList.append(m[:,len(Matrice[0]):])\n", + "\n", + "al.printEquMatricesAug(MatriceList,RhSList)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\left(\\begin{array}{cccc| ccc} 1 & 2 & 3 & 0 & 1 & 5 \\\\4 & 5 & 6 & 0 & 2 & 6 \\\\7 & 6 & 8 & 0 & 3 & 7 \\end{array}\\right)$" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "import numpy as np\n", + "import AL_Fct as al\n", + "from IPython.display import display, Latex\n", + "\n", + "Matrice=[[1,2,3,0],[4,5,6,0],[7,6,8,0]]\n", + "b=[[1,5],[2,6], [3,7]]\n", + "\n", + "texA='$'+ al.texMatrixAug(Matrice,b) + '$'\n", + "display(Latex(texA)) \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": true + }, + "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.7.3" + } + }, + "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 fa2469b..9889ab2 100644 --- a/Chapitre 1 - Systemes equations lineaires/AL_Fct.py +++ b/Chapitre 1 - Systemes equations lineaires/AL_Fct.py @@ -1,361 +1,401 @@ #!/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, display @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 - -#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(n,coeff,b):# Latex Print of one equation in format a1x1+ ...+anxn or with coefficients. coeff=coeff+b texEq='$' texEq=texEq+ strEq(n,coeff) texEq=texEq + '$' display(Latex(texEq)) -def printSyst(m,n,MatCoeff,b):# Latex Print of one system of m equation in format ai1x1+ ...+ainxn=bi or with coeff in MatCoeff. - if (str(MatCoeff)=='') or (len(MatCoeff[1])==n and len(MatCoeff)==m): #ensures that MatCoeff has proper dimensions +def printSyst(m,n,A,b):# Latex Print of one system of m equation in format ai1x1+ ...+ainxn=bi or with coeff in MatCoeff. + if (str(A)=='') or (len(A[1])==n and len(A)==m): #ensures that MatCoeff has proper dimensions texSyst='$\\begin{cases}' Eq_list=[] - MatCoeff = [MatCoeff[i]+[b[i]]for i in range(0,m)] - MatCoeff=np.array(MatCoeff) #just in case it's not + 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(MatCoeff)=='': + 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,MatCoeff[i,:]) + Eq_i=strEq(n,A[i,:]) 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(A): #return tex expression of one matrix +def texMatrix(A): #return tex expression of one matrix of coefficients + 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)' return texA + +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 printA(A) : #Print matrix texA='$'+ texMatrix(A) + '$' # print(texA) display(Latex(texA)) + + +def printAAug(A,b) : #Print matrix (A|b) + texA='$'+ texMatrixAug(A,b) + '$' + # print(texA) + display(Latex(texA)) def printEquMatrices(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 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,MatriceCoeff,b): - MatriceCoeff = [MatriceCoeff[i]+[b[i]] for i in range(0,len(MatriceCoeff))] - MatriceCoeff=np.array(MatriceCoeff) - isSol=[SolOfEq(solution, MatriceCoeff[i,:],i+1) for i in range(0,len(MatriceCoeff))] +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,MatCoeff,b): # small values for p allows for dots to be seen - MatCoeff = [MatCoeff[i]+[b[i]] for i in range(0,len(MatCoeff))] - MatCoeff=np.array(MatCoeff) +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(MatCoeff)+1): - if (abs(MatCoeff[i-1,1])) > abs (MatCoeff[i-1,0]) : - trace=go.Scatter(x=t, y= (MatCoeff[i-1,2]-MatCoeff[i-1,0]*t)/MatCoeff[i-1,1], name='Droite %d'%i) + for i in range(1,len(A)+1): + if (abs(A[i-1,1])) > abs (A[i-1,0]) : + 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=(MatCoeff[i-1,2]-MatCoeff[i-1,1]*t)/MatCoeff[i-1,0], y= t, name='Droite %d'%i) + 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,MatCoeff,b): # small values for p allows for dots to be seen - MatCoeff = [MatCoeff[i]+[b[i]] for i in range(0,len(MatCoeff))] - MatCoeff=np.array(MatCoeff) + + +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(MatCoeff)): + 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(MatCoeff[i,2])) > abs (MatCoeff[i,1]) : # z en fonction de x,y + 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=(MatCoeff[i,3]-MatCoeff[i,0]*x -MatCoeff[i,1]*y)/MatCoeff[i,2], + 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 (MatCoeff[i,2]==0 and MatCoeff[i,1]==0): # x =b + elif (A[i,2]==0 and A[i,1]==0): # x =b y = sGrid z = tGrid - surface = go.Surface(x=MatCoeff[i,3]-MatCoeff[i,1]*y, y=y, z=z, + 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=(MatCoeff[i,3]-MatCoeff[i,0]*x -MatCoeff[i,2]*z)/MatCoeff[i,1], z=z, + 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(MatCoeff,b): #Nous donne la matrice echelonne d un system [A|b] - MatCoeff = [MatCoeff[i]+[b[i]] for i in range(0,len(MatCoeff))] - Mat=np.array(MatCoeff) +def echelonMat(A,b): #Nous donne la matrice echelonne d un system [A|b] + A = [A[i]+[b[i]] for i in range(0,len(A))] + 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([MatCoeff, Mat]) + printEquMatrices([A, 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(MatCoeff)): + 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)) return np.asmatrix(Mat) -def echelonMatCoeff(MatCoeff): #take echelonMAt but without b. - b= [0 for i in range(len(MatCoeff))] - Mat = [MatCoeff[i]+[b[i]] for i in range(0,len(MatCoeff))] +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(MatCoeff), np.asmatrix(Mat[:, :len(MatCoeff[0])])]) + 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(MatCoeff)): + 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(MatCoeff[0])])) + printA(np.asmatrix(Mat[:, :len(A[0])])) return np.asmatrix(Mat) -def echelonRedMat(MatCoeff, b): - Mat=echelonMat(MatCoeff,b) +def echelonRedMat(A, b): + Mat=echelonMat(A,b) Mat=np.array(Mat) - MatAugm = [MatCoeff[i]+[b[i]] for i in range(0,len(MatCoeff))] + 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 Mat -def f(a,x): - return x+ a \ No newline at end of file diff --git a/Chapitre 1 - Systemes equations lineaires/Tests/.ipynb_checkpoints/Untitled-checkpoint.ipynb b/Chapitre 1 - Systemes equations lineaires/Tests/.ipynb_checkpoints/Untitled-checkpoint.ipynb deleted file mode 100644 index cb1694a..0000000 --- a/Chapitre 1 - Systemes equations lineaires/Tests/.ipynb_checkpoints/Untitled-checkpoint.ipynb +++ /dev/null @@ -1,135 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 40, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "80864d943ac9434d845064cfb5e500a2", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "interactive(children=(RadioButtons(description='Pizza topping:', options=('pepperoni', 'pineapple', 'anchovies…" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "import ipywidgets as widgets\n", - "import numpy as np\n", - "from ipywidgets import interact, interactive, fixed, interact_manual\n", - "\n", - "r=widgets.RadioButtons(\n", - " options=['pepperoni', 'pineapple', 'anchovies'],\n", - "# value='pineapple',\n", - " description='Pizza topping:',\n", - " disabled=False\n", - ")\n", - "i=widgets.IntText(\n", - " value=7,\n", - " min=0,\n", - " max=10,\n", - " step=1,\n", - " description='Any:',\n", - " disabled=False\n", - ")\n", - "j=widgets.IntText(\n", - " value=7,\n", - " min=0,\n", - " max=10,\n", - " step=1,\n", - " description='Any:',\n", - " disabled=False\n", - ")\n", - "alpha=widgets.FloatText(\n", - " value=7,\n", - " min=0,\n", - " max=10,\n", - " step=1,\n", - " description='Any:',\n", - " disabled=False\n", - ")\n", - "def f(w1,w2):\n", - " print(w1, w2)\n", - " return w1,w2\n", - "w = interactive(f, w1=r, w2=a)\n", - "w" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntText(value=7, description='Any:')\n" - ] - } - ], - "source": [ - "print(a)" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "metadata": {}, - "outputs": [], - "source": [ - "from tkinter import * # or tkinter if you use Python3\n", - "\n", - "root = Tk()\n", - "\n", - "label_1 = Label(master=root, text='Name 1')\n", - "label_2 = Label(master=root, text='Name 2')\n", - "label_3 = Label(master=root, text='Name 3')\n", - "label_4 = Label(master=root, text='Name 4')\n", - "\n", - "label_1.grid(row=0)\n", - "label_2.grid(row=1)\n", - "label_3.grid(row=2) # this is the 2nd\n", - "label_4.grid(row=4) # this is the 4th\n", - "\n", - "root.rowconfigure(index=3, weight=1) # add weight to the 3rd!\n", - "root.mainloop()" - ] - }, - { - "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.7.3" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/Chapitre 1 - Systemes equations lineaires/Tests/Untitled.ipynb b/Chapitre 1 - Systemes equations lineaires/Tests/Untitled.ipynb deleted file mode 100644 index a292d53..0000000 --- a/Chapitre 1 - Systemes equations lineaires/Tests/Untitled.ipynb +++ /dev/null @@ -1,153 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 72, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "c575ab1265ff4d1486bae9f516679e3f", - "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": [ - "import ipywidgets as widgets\n", - "import numpy as np\n", - "from ipywidgets import interact, interactive, fixed, interact_manual\n", - "\n", - "r=widgets.RadioButtons(\n", - " options=['Eij', 'Ei(alpha)', 'Eij(alpha)'],\n", - "# value='pineapple',\n", - " description='Opération:',\n", - " disabled=False\n", - ")\n", - "i=widgets.IntText(\n", - " value=7,\n", - " min=0,\n", - " max=10,\n", - " step=1,\n", - " description='Ligne i:',\n", - " disabled=False\n", - ")\n", - "j=widgets.IntText(\n", - " value=7,\n", - " min=0,\n", - " max=10,\n", - " step=1,\n", - " description='Ligne j:',\n", - " disabled=False\n", - ")\n", - "alpha=widgets.FloatText(\n", - " value=0.5,\n", - " step=0.1,\n", - " description='Coeff. alpha:',\n", - " disabled=False\n", - ")\n", - "\n", - "Matrice=2\n", - "\n", - "def f(w1,w2,w3,w4, w5):\n", - " w5+=w5\n", - " print(w5)\n", - " if w4==0:\n", - " print('Le coefficient alpha doit être non-nul!')\n", - " return\n", - " if w1=='Eij':\n", - " print('Opération élémentaire', w1, 'échange la ligne', w2,' avec la ligne ',w3)\n", - " if w1=='Ei(alpha)':\n", - " print('Opération élémentaire', w1, 'multiplie la ligne', w3,' par',w4 )\n", - " if w1=='Eij(alpha)':\n", - " print('Opération élémentaire', w1, 'additionne', w4,' fois la ligne ',w3, 'à la ligne',w2 )\n", - " return w1,w2,w3,w4,w5\n", - "\n", - "\n", - "w = interactive(f, w1=r, w2=i,w3=j,w4=alpha, w5=fixed(Matrice))\n", - "w" - ] - }, - { - "cell_type": "raw", - "metadata": {}, - "source": [] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntText(value=7, description='Any:')\n" - ] - } - ], - "source": [ - "print(a)" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "metadata": {}, - "outputs": [], - "source": [ - "from tkinter import * # or tkinter if you use Python3\n", - "\n", - "root = Tk()\n", - "\n", - "label_1 = Label(master=root, text='Name 1')\n", - "label_2 = Label(master=root, text='Name 2')\n", - "label_3 = Label(master=root, text='Name 3')\n", - "label_4 = Label(master=root, text='Name 4')\n", - "\n", - "label_1.grid(row=0)\n", - "label_2.grid(row=1)\n", - "label_3.grid(row=2) # this is the 2nd\n", - "label_4.grid(row=4) # this is the 4th\n", - "\n", - "root.rowconfigure(index=3, weight=1) # add weight to the 3rd!\n", - "root.mainloop()" - ] - }, - { - "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.7.3" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/Chapitre 1 - Systemes equations lineaires/Untitled.ipynb b/Chapitre 1 - Systemes equations lineaires/Untitled.ipynb new file mode 100644 index 0000000..bd82bb0 --- /dev/null +++ b/Chapitre 1 - Systemes equations lineaires/Untitled.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1. 2.]\n", + " [2. 3.]] [[1. 2.]\n", + " [2. 3.]]\n" + ] + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "c9e86c5fb43846df99ca8fdf750cdc63", + "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" + }, + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import ipywidgets as widgets\n", + "import numpy as np\n", + "from ipywidgets import interact, interactive, fixed, interact_manual\n", + "import AL_Fct as al\n", + "\n", + "r=widgets.RadioButtons(\n", + " options=['Eij', 'Ei(alpha)', 'Eij(alpha)'],\n", + "# value='pineapple',\n", + " description='Opération:',\n", + " disabled=False\n", + ")\n", + "\n", + "\n", + "alpha=widgets.Text(\n", + " value='1',\n", + " description='Coeff. alpha:',\n", + " disabled=False\n", + ")\n", + "\n", + "Matrice=[[1,2],[2,3]]\n", + "\n", + "Matrice=np.array(Matrice)\n", + "Matrice=Matrice.astype(float)\n", + "\n", + "i=widgets.BoundedIntText(\n", + " value=1,\n", + " min=0,\n", + " max=len(Matrice),\n", + " step=1,\n", + " description='Ligne i:',\n", + " disabled=False\n", + ")\n", + "\n", + "j=widgets.BoundedIntText(\n", + " value=1,\n", + " min=0,\n", + " max=len(Matrice),\n", + " step=1,\n", + " description='Ligne j:',\n", + " disabled=False\n", + ")\n", + "a= 1;\n", + "a=np.copy(Matrice)\n", + "print(a, Matrice)\n", + "def f(w1,w2,w3,w4,w5):\n", + " i,j=al.python2matlab(w2,w3)\n", + " print(a, Matrice)\n", + " w4=eval(w4)\n", + " if w4==0:\n", + " print('Le coefficient alpha doit être non-nul!')\n", + " return\n", + " if w1=='Eij':\n", + " w5=al.Eij(w5,i,j)\n", + " al.printEquMatrices([Matrice,w5,a])\n", + " print('Opération élémentaire', w1, 'échange la ligne', w2,' avec la ligne ',w3)\n", + " if w1=='Ei(alpha)':\n", + " w5=al.Ealpha(w5,i,w4)\n", + " al.printEquMatrices([Matrice2,w5])\n", + " print('Opération élémentaire', w1, 'multiplie la ligne', w3,' par',w4 )\n", + " if w1=='Eij(alpha)':\n", + " w5=al.Eijalpha(w5,i,j,w4)\n", + " al.printEquMatrices([Matrice2,w5])\n", + " print('Opération élémentaire', w1, 'additionne', w4,' fois la ligne ',w3, 'à la ligne',w2 )\n", + "\n", + "\n", + "interact_manual(f, w1=r, w2=i,w3=j,w4=alpha, w5=fixed(Matrice))\n" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\left(\\begin{array}{ccc} 1 & 2 & 3 \\\\0 & -3 & -6 \\\\0 & -6 & -12 \\end{array}\\right)$" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/latex": [ + "$\\left(\\begin{array}{ccc} 1 & 2 & 3 \\\\0 & 1 & 2 \\\\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\n" + ] + }, + { + "data": { + "text/latex": [ + "$\\left(\\begin{array}{ccc} 1 & 2 & 3 \\\\4 & 5 & 6 \\\\7 & 8 & 9 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccc} 1 & 2 & 3 \\\\0 & 1 & 2 \\\\0 & 0 & 0 \\end{array}\\right)$" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "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)$" + ], + "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": "9f0192c852b24dd7b9070b24224aa32d", + "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": "f719950679d044fdb60023ec131a8dcf", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "BoundedIntText(value=1, description='Ligne i:', max=3, min=1)" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "89e1b66478494a0093774cbfcd1e8a11", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "BoundedIntText(value=1, description='Ligne j:', max=3, min=1)" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "58f37420dc014bb88a2cbeaabd92ff66", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Text(value='1', description='Coeff. alpha:')" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "\n", + "import ipywidgets as widgets\n", + "import numpy as np\n", + "from ipywidgets import interact, interactive, fixed, interact_manual\n", + "import AL_Fct as al\n", + "Matrice=[[1,2,3],[4,5,6],[7,8,9]]\n", + "b=[[1,0,0],[0,1,0], [0,0,1]]\n", + "\n", + "\n", + "Matrice=np.array(Matrice).astype(float)\n", + "b=np.array(b).astype(float)\n", + "\n", + "\n", + "print('Vous allez échelonner la matrice')\n", + "al.printAAug(Matrice,b)\n", + "j=widgets.BoundedIntText(\n", + " value=1,\n", + " min=1,\n", + " max=len(Matrice),\n", + " step=1,\n", + " description='Ligne j:',\n", + " disabled=False\n", + ")\n", + "i=widgets.BoundedIntText(\n", + " value=1,\n", + " min=1,\n", + " max=len(Matrice),\n", + " step=1,\n", + " description='Ligne i:',\n", + " disabled=False\n", + ")\n", + "\n", + "r=widgets.RadioButtons(\n", + " options=['Eij', 'Ei(alpha)', 'Eij(alpha)'],\n", + " description='Opération:',\n", + " disabled=False\n", + ")\n", + "\n", + "\n", + "alpha=widgets.Text(\n", + " value='1',\n", + " description='Coeff. alpha:',\n", + " disabled=False\n", + ")\n", + "\n", + "print(\"Régler les paramètres et évaluer la cellule suivante\")\n", + "print(\"Répéter cela jusqu'à obtenir une forme échelonnée réduite\")\n", + "display(r)\n", + "display(i)\n", + "display(j)\n", + "display(alpha)\n", + "\n", + "m=np.concatenate((Matrice,b), axis=1)\n", + "\n", + "MatriceList=[Matrice]\n", + "RhSList=[b]\n" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "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 \\\\0 & -3 & -6 & -4 & 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 \\\\0 & -3 & -6 & -4 & 1 & 0 \\\\0 & -6 & -12 & -7 & 0 & 1 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\0 & -3 & -6 & -4 & 1 & 0 \\\\0 & 6 & 12 & 7 & 0 & -1 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\0 & 3 & 6 & 4 & -1 & 0 \\\\0 & 6 & 12 & 7 & 0 & -1 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\0 & 3 & 6 & 4 & -1 & 0 \\\\0 & 0 & 0 & -1 & 2 & -1 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\0 & 3 & 6 & 4 & -1 & 0 \\\\0 & 0 & 0 & -0.333 & 0.667 & -0.333 \\end{array}\\right)\\quad \\sim \\quad\\left(\\begin{array}{ccc| cccc} 1 & 2 & 3 & 1 & 0 & 0 \\\\0 & 1 & 2 & 1.333 & -0.333 & 0 \\\\0 & 0 & 0 & -0.333 & 0.667 & -0.333 \\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(Matrice[0])])\n", + "RhSList.append(m[:,len(Matrice[0]):])\n", + "\n", + "al.printEquMatricesAug(MatriceList,RhSList)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\left(\\begin{array}{cccc| ccc} 1 & 2 & 3 & 0 & 1 & 5 \\\\4 & 5 & 6 & 0 & 2 & 6 \\\\7 & 6 & 8 & 0 & 3 & 7 \\end{array}\\right)$" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": true + }, + "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.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Chapitre 1 - Systemes equations lineaires/__pycache__/AL_Fct.cpython-37.pyc b/Chapitre 1 - Systemes equations lineaires/__pycache__/AL_Fct.cpython-37.pyc index fb3b60c..6348411 100644 Binary files a/Chapitre 1 - Systemes equations lineaires/__pycache__/AL_Fct.cpython-37.pyc and b/Chapitre 1 - Systemes equations lineaires/__pycache__/AL_Fct.cpython-37.pyc differ