Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. def bwd_subs( U, y ):
  2.     """Solve the linear system Ux = y with upper triangular matrix U by forward substitution."""
  3.     n = U.shape[0]
  4.     result = np.zeros(n) # initiate an array of the same length as y filled with zeros as floats
  5.     n = n - 1 # Because Indices start at 0
  6.     result[n] = y[n] / U[n, n] # get the last coefficient
  7.     for j in range(n, -1, -1): # iterate backwards through the rows
  8.         help = 0.0
  9.         for k in range(j + 1, n + 1): # iterate through all of the known values
  10.             help = U[j, k] * result[k] + help # sum up all of the known values
  11.         result[j] = (1 / U[j, j]) * (y[j] - help) # formula from the script
  12.  
  13.     return result # return an array with all of the coefficients
  14.  
  15. def gauss_solve( A, b ):
  16.     """Solve the linear system Ax=b using direct Gaussian elimination and backward substitution."""
  17.    
  18.     n = A.shape[0]
  19.     bCopy = np.copy(b)
  20.     n = n - 1 # Because Indices start at 0
  21.     for i in range(0, n): # iterate through your matrix
  22.         if A[i, i] == 0.: # if the value at this spot is 0 you cannot apply the algorithm
  23.             for i2 in range(i + 1, n + 1): # check the following rows because you cannot pick one from before
  24.                 if A[i2, i] != 0.: # if 1 is found
  25.                     A[[i, i2]] = A[[i2, i]] # swap the rows
  26.                     bCopy[[i, i2]] = bCopy[[i2, i]] # swap the rows
  27.                     break # no need to search for more
  28.         for i3 in range(i + 1, n + 1): # perform the algorithm
  29.             factor = A[i3, i] / A[i, i] # the times you have to subtract the first row
  30.             A[i3] = A[i3] - (factor * A[i]) # subtract the first row factor times
  31.             bCopy[i3] = bCopy[i3] - (factor * bCopy[i]) # same for the results
  32.    
  33.     return bwd_subs(A, bCopy) # now that they are in the right form we can solve them
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement