fork download
  1. import numpy as np
  2.  
  3. # Step 1: Read size of matrix
  4. n = int(input("Enter the order of square matrix: "))
  5.  
  6. # Step 2: Input Coefficient Matrix A and Constant Vector B
  7. print("Enter coefficients of matrix A:")
  8. A = []
  9. for i in range(n):
  10. row = list(map(float, input().split()))
  11. if len(row) != n:
  12. print("Please enter exactly", n, "coefficients.")
  13. exit()
  14. A.append(row)
  15.  
  16. print("Enter constants of vector B:")
  17. B = list(map(float, input().split()))
  18. if len(B) != n:
  19. print("Please enter exactly", n, "constants.")
  20. exit()
  21.  
  22. A = np.array(A)
  23. B = np.array(B)
  24.  
  25. # Step 3: Calculate determinant of A
  26. detA = np.linalg.det(A)
  27. print("\nDeterminant of A: {:.3f}".format(detA))
  28.  
  29. # Step 4: Check solvability
  30. if detA == 0:
  31. print("Matrix is singular; the system is not uniquely solvable.")
  32. exit()
  33.  
  34. # Step 5: Solve using Cramer's Rule
  35. solution = []
  36. for i in range(n):
  37. Ai = A.copy()
  38. Ai[:, i] = B
  39. detAi = np.linalg.det(Ai)
  40. xi = detAi / detA
  41. solution.append(xi)
  42.  
  43. # Step 6: Display the solution
  44. print("\nThe solution using Cramer's Rule:")
  45. for i, x in enumerate(solution):
  46. print(f"x{i+1} = {x:.6f}")
  47.  
  48. # Step 7 & 8: Calculate and display inverse of A
  49. inverseA = np.linalg.inv(A)
  50. print("\nInverse of matrix A:")
  51. for row in inverseA:
  52. print(" ".join(f"{val:.4f}" for val in row))
  53.  
Success #stdin #stdout 0.78s 41500KB
stdin
2
2 5 -3 1
11 -4 
stdout
Enter the order of square matrix: Enter coefficients of matrix A:
Please enter exactly 2 coefficients.