Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. """ Calcul le polynome caractéristique d'une matrice,
  2. codé avec la contrainte de ne pas utiliser numpy
  3. ne vérfie pas si la matrice envoyée est légale
  4.  
  5. Adrien B. - 2017"""
  6.  
  7. def multiply(A, B): # Multiplication matricielle canonique
  8.  
  9. R = [[0 for i in range(len(B[0]))] for j in range(len(A))]
  10.  
  11. for i in range(len(A)):
  12. for j in range(len(B[0])):
  13. for k in range(len(B)):
  14. R[i][j] += A[i][k] * B[k][j]
  15.  
  16. return R
  17.  
  18. def delta(i, j): #symbole de Kronecker
  19. if i == j:
  20. return 1
  21. else:
  22. return 0
  23.  
  24. def id(n): # matrice identite de rang n
  25. return [[delta(i,j) for i in range(n)] for j in range(n)]
  26.  
  27. # l1 <- mu1 * l1 + mu2 <- l2
  28. # effectue les operations sur un tableau de matrices en ligne
  29. def opLigne(matriceLigne, l1, mu1, l2, mu2):
  30.  
  31. for i in range(len(matriceLigne[0])):
  32. matriceLigne[l1][i] = mu1 * matriceLigne[l1][i] + mu2 * matriceLigne[l2][i]
  33.  
  34. def lineify(A): # transforme une matrice en tableau de nombres 1D
  35. R = []
  36.  
  37. for i in range(len(A)):
  38. for j in range(len(A[0])):
  39. R.append(A[i][j])
  40.  
  41. return R
  42.  
  43. def polMin(A): #calcul le polynome minimal d'une matrice
  44.  
  45. n = len(A)
  46. M, compagnon, ligneNulle = id(n), id(n+1), [0] * n * n
  47. puissances = [lineify(M)]
  48. for i in range(n):
  49. M = multiply(M, A)
  50. puissances.append(lineify(M))
  51.  
  52. i = 0
  53. while puissances[i] != ligneNulle:
  54. pivot = 0
  55. while puissances[i][pivot] == 0:
  56. pivot += 1
  57.  
  58. for j in range(i + 1, n+1):
  59. opLigne(compagnon, j, puissances[i][pivot], i, - puissances[j][pivot])
  60. opLigne(puissances, j, puissances[i][pivot], i, - puissances[j][pivot])
  61.  
  62. i += 1
  63.  
  64. res = compagnon.pop()
  65. dom = res[len(res)-1]
  66. return [i / dom for i in res] # on renvoie la solution sous forme d'un polynome unitaire
  67.  
  68. def printPolynome(P): # affiche joliment(-ish) les polynomes
  69. res = ""
  70.  
  71. for i in range(len(P)):
  72. tmp = ""
  73. if P[i] == 1:
  74. tmp = "+ "
  75. elif P[i] == -1:
  76. tmp = "- "
  77. elif P[i] > 0:
  78. tmp = "+ " + str(P[i])
  79. elif P[i] < 0:
  80. tmp = "- " + str(abs(P[i]))
  81.  
  82. if tmp == "":
  83. continue
  84.  
  85. if i == 1:
  86. res = tmp + "X " + res
  87. elif i == 0:
  88. res = " " + res
  89. elif i >= 2:
  90. res = tmp + "X^" + str(i) + " " + res
  91.  
  92. return res
  93.  
  94. matrix = [
  95. [1, -1, 3],
  96. [2, 4, 4],
  97. [23, 12, 9]
  98. ]
  99.  
  100. print(printPolynome(polMin(matrix)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement