Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- def solveEqns(A, v):
- """This function uses Gaussian Elimination with partial pivoting to solve
- systems of linear equations of the form Ax = v"""
- n = len(A)
- L = len(v)
- Pivot = A[0][0] # Set the (1,1) element of A as our Pivot
- count = -1 #The count will tell us the column in which our pivot lives.
- for j in range(0, n):
- Pivot = A[0][j]
- count += 1 #Count has the same value as j, i.e. the column of the pivot.
- if not all (A[i][j] == 0 for i in range(0, n)):
- #check if all elements in column are 0
- break
- maxEl = abs(Pivot)
- #Now we ensure the element in the column with highest absolute value
- #is at the top
- for k in range(0, n):
- if abs(A[k][count]) >= maxEl:
- maxEl = abs(A[k][count])
- maxRow = k
- else:
- maxRow = 0
- #Swap row with maximum element with current top row, column by column.
- for i in range(0, n):
- tmp = A[maxRow][i]
- A[maxRow][i] = A[0][i]
- A[0][i] = tmp
- #Swap the corresponding elements in v to ensure our equations still hold.
- tmp2 = v[maxRow]
- v[maxRow] = v[0]
- v[0] = tmp2
- print(A)
- print(v)
- for k in range(L):
- if A[k][k] == 0:
- div = 1 #prevents us dividing by 0 if we have a column of 0s
- else:
- div = A[k][k]
- A[k, :] /= div
- v[k] /= div
- for i in range(k+1, L):
- mult = A[i][k]
- A[i, :] -= mult*A[k, :]
- v[i] -= mult*v[k]
- #Substitute back in
- x = np.empty(L, float)
- for k in range(L-1, -1, -1):
- x[k] = v[k]
- for i in range(k+1, L):
- x[k] -= A[k, i]*x[i]
- print(x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement