Advertisement
Guest User

Untitled

a guest
Dec 6th, 2016
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def solveEqns(A, v):
  4. """This function uses Gaussian Elimination with partial pivoting to solve
  5. systems of linear equations of the form Ax = v"""
  6.  
  7. n = len(A)
  8. L = len(v)
  9.  
  10. Pivot = A[0][0] # Set the (1,1) element of A as our Pivot
  11.  
  12. count = -1 #The count will tell us the column in which our pivot lives.
  13. for j in range(0, n):
  14. Pivot = A[0][j]
  15. count += 1 #Count has the same value as j, i.e. the column of the pivot.
  16. if not all (A[i][j] == 0 for i in range(0, n)):
  17. #check if all elements in column are 0
  18. break
  19.  
  20. maxEl = abs(Pivot)
  21.  
  22.  
  23. #Now we ensure the element in the column with highest absolute value
  24. #is at the top
  25. for k in range(0, n):
  26. if abs(A[k][count]) >= maxEl:
  27. maxEl = abs(A[k][count])
  28. maxRow = k
  29. else:
  30. maxRow = 0
  31.  
  32.  
  33. #Swap row with maximum element with current top row, column by column.
  34. for i in range(0, n):
  35. tmp = A[maxRow][i]
  36. A[maxRow][i] = A[0][i]
  37. A[0][i] = tmp
  38.  
  39. #Swap the corresponding elements in v to ensure our equations still hold.
  40. tmp2 = v[maxRow]
  41. v[maxRow] = v[0]
  42. v[0] = tmp2
  43.  
  44. print(A)
  45. print(v)
  46.  
  47. for k in range(L):
  48. if A[k][k] == 0:
  49. div = 1 #prevents us dividing by 0 if we have a column of 0s
  50. else:
  51. div = A[k][k]
  52.  
  53. A[k, :] /= div
  54. v[k] /= div
  55.  
  56. for i in range(k+1, L):
  57. mult = A[i][k]
  58. A[i, :] -= mult*A[k, :]
  59. v[i] -= mult*v[k]
  60.  
  61.  
  62. #Substitute back in
  63. x = np.empty(L, float)
  64. for k in range(L-1, -1, -1):
  65. x[k] = v[k]
  66. for i in range(k+1, L):
  67. x[k] -= A[k, i]*x[i]
  68.  
  69. print(x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement