EWTD

TridiagonalMatrixAlgorythm

Feb 28th, 2023
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.85 KB | None | 0 0
  1. import numpy
  2.  
  3. def tridiagonalMatrixAlgorythm(d, c, a, b):
  4.     alpha = [0]
  5.     beta = [0]
  6.     n = len(b)
  7.  
  8.     for i in range(1, n-1):
  9.         if i == 1:
  10.             alpha.append(-c[i] / d[i])
  11.             beta.append(b[i] / d[i])
  12.         else:
  13.             alpha.append(-c[i] / (d[i] + alpha[i-1] * a[i-1]))
  14.             beta.append((b[i] - a[i-1] * beta[i-1]) / (d[i] + a[i-1] * alpha[i-1]))
  15.  
  16.     x = [0] * n
  17.     n -= 1
  18.     x[n] = (b[n] - a[n-1] * beta[n-1]) / (d[n] + a[n-1] * alpha[n-1])
  19.     for i in range(n-1, 0, -1):
  20.         x[i] = x[i+1] * alpha[i] + beta[i]
  21.     return x[1:]
  22.  
  23. def init_array(matrix, D):
  24.     a, b, c, d = [0], [0], [0], [0]
  25.     d.extend([matrix[i][i] for i in range(len(matrix[0]))])
  26.     c.extend([matrix[i][i + 1] for i in range(len(matrix[0]) - 1)])
  27.     a.extend([matrix[i + 1][i] for i in range(len(matrix[0]) - 1)])
  28.     b.extend(D)
  29.     return a, b, c, d
  30.  
  31. def valueB(matrix, x):
  32.     b = [0] * len(x)
  33.     for j in range(len(matrix)):
  34.         b[j] = sum(matrix[j][i] * x[i] for i in range(len(matrix[j])))
  35.     return b
  36.  
  37. def find_error(matrix, d1, d2, x2):
  38.     r = [d2[i] - d1[i] for i in range(len(matrix))]
  39.     matrix_rev = numpy.matrix(matrix).I
  40.     matrix_rev = matrix_rev.tolist()
  41.     e = [0 for _ in range(0, len(d1))]
  42.     for j in range(0, len(matrix_rev)):
  43.         e[j] = sum(matrix_rev[j][i] * r[i] for i in range(len(matrix_rev[j])))
  44.  
  45.     x = [x2[i] - e[i] for i in range(0, len(matrix_rev))]
  46.     return x, e[0:4]
  47.  
  48.  
  49. if __name__ == "__main__":
  50.     matrix = [[4, 1, 0, 0],
  51.               [1, 4, 1, 0],
  52.               [0, 1, 4, 1],
  53.               [0, 0, 1, 4]]
  54.     D = [5, 6, 6, 5]
  55.     a, b, c, d = init_array(matrix, D)
  56.     x = tridiagonalMatrixAlgorythm(d, c, a, b)
  57.     print(x)
  58.     D_ = valueB(matrix, x)
  59.     print(D_)
  60.     x_real, error = find_error(matrix, D, D_, x)
  61.     print(error)
  62.     print(x_real)
  63.  
Add Comment
Please, Sign In to add comment