fork download
  1. # Name : Ananda Das;
  2. # ID : 230241053;
  3. # Lab : 3 , problem : 02;
  4. def lu_decomposition(A, n):
  5. L = [[0.0] * n for _ in range(n)]
  6. U = [[0.0] * n for _ in range(n)]
  7.  
  8. for i in range(n):
  9. L[i][i] = 1.0
  10.  
  11. for j in range(n):
  12. for i in range(n):
  13. if i <= j:
  14. U[i][j] = A[i][j] - sum(L[i][k] * U[k][j] for k in range(i))
  15. else:
  16. if abs(U[j][j]) < 1e-10:
  17. print("Matrix is singular or nearly singular. Cannot proceed with LU Decomposition.")
  18. exit()
  19. L[i][j] = (A[i][j] - sum(L[i][k] * U[k][j] for k in range(j))) / U[j][j]
  20. return L, U
  21.  
  22. def forward_substitution(L, B, n):
  23. Y = [0.0] * n
  24. for i in range(n):
  25. Y[i] = B[i] - sum(L[i][j] * Y[j] for j in range(i))
  26. return Y
  27.  
  28. def backward_substitution(U, Y, n):
  29. X = [0.0] * n
  30. for i in reversed(range(n)):
  31. if abs(U[i][i]) < 1e-10:
  32. print("Zero on diagonal during backward substitution. No unique solution.")
  33. exit()
  34. X[i] = (Y[i] - sum(U[i][j] * X[j] for j in range(i + 1, n))) / U[i][i]
  35. return X
  36.  
  37. def print_matrix(name, matrix):
  38. print(f"[{name}]:")
  39. for row in matrix:
  40. print(" ".join(f"{val:.3f}" for val in row))
  41. print()
  42.  
  43. def print_vector(name, vector):
  44. print(f"[{name}]:", " ".join(f"{val:.3f}" for val in vector))
  45. print()
  46.  
  47. # Main program
  48. n = int(input("Enter the order of square matrix: "))
  49. print("Enter matrix elements row-wise:")
  50. A = [list(map(float, input().split())) for _ in range(n)]
  51. B = list(map(float, input("Enter the constant terms: ").split()))
  52.  
  53. L, U = lu_decomposition(A, n)
  54. Y = forward_substitution(L, B, n)
  55. X = backward_substitution(U, Y, n)
  56.  
  57. print_matrix("L", L)
  58. print_matrix("U", U)
  59. print_vector("Y", Y)
  60. print_vector("X", X)
  61.  
Success #stdin #stdout 0.09s 14116KB
stdin
3
2 4 -2
4 9 -3
-2 -3 -7
2 8 10
stdout
Enter the order of square matrix: Enter matrix elements row-wise:
Enter the constant terms: [L]:
1.000 0.000 0.000
2.000 1.000 0.000
-1.000 1.000 1.000

[U]:
2.000 4.000 -2.000
0.000 1.000 1.000
0.000 0.000 -10.000

[Y]: 2.000 4.000 8.000

[X]: -9.400 4.800 -0.800