gpt-4-0314· openai
Suzhen/CodeChat
Write a Python program which solves a system of linear equations using the numpy…
- User
Write a Python program which solves a system of linear equations using the numpy package. The program prompts the user for a square matrix and a column vector. Then the program solves the linear matrix equation using both the
numpy.linalg.solvefunction and the Cramer's rule - Assistant
Here is a Python program that solves a system of linear equations using the numpy package and Cramer's rule.
import numpy as np def get_input_matrix(matrix_type): size = int(input(f"Enter the size of the {matrix_type} matrix: ")) matrix = [] print(f"Enter the {matrix_type} matrix, one row at a time, separated by spaces:") for i in range(size): row = list(map(float, input().split())) matrix.append(row) return np.array(matrix) def cramer_rule(matrix, column): det_matrix = np.linalg.det(matrix) if det_matrix == 0: print("The system has no unique solution using Cramer's rule.") return None result = [] for i in range(matrix.shape[0]): temp_matrix = matrix.copy() temp_matrix[:, i] = column det_temp_matrix = np.linalg.det(temp_matrix) result.append(det_temp_matrix / det_matrix) return np.array(result) def main(): matrix = get_input_matrix("square") column = get_input_matrix("column").flatten() try: np_solution = np.linalg.solve(matrix, column) print("\nSolution using numpy.linalg.solve:") print(np_solution) except np.linalg.LinAlgError: print("\nThe system has no unique solution using numpy.linalg.solve.") cramer_solution = cramer_rule(matrix, column) if cramer_solution is not None: print("\nSolution using Cramer's rule:") print(cramer_solution) if __name__ == "__main__": main()