Output:
import numpy as np def solve_equations(): equation1 = input("Enter equation 1 (use x0 and x1 as variables): ") equation2 = input("Enter equation 2 (use x0 and x1 as variables): ") # Define the coefficients and constants arrays coeffs = [] constants = [] # Parse equation 1 equation_terms = equation1.split('=') equation_vars = set() for term in equation_terms[0].split('+'): if term.startswith('-'): term = '-' + term[1:].replace('-', '+-') if 'x' in term: equation_vars.add(term) coeffs.append(eval(term.replace('x0', '0').replace('x1', '1'))) else: constants.append(float(term)) # Parse equation 2 equation_terms = equation2.split('=') for term in equation_terms[0].split('+'): if term.startswith('-'): term = '-' + term[1:].replace('-', '+-') if 'x' in term: equation_vars.add(term) coeffs.append(eval(term.replace('x0', '0').replace('x1', '1'))) else: constants.append(float(term)) num_vars = len(equation_vars) # Create the coefficient matrix and constants vector if num_vars == 2: A = np.array(coeffs).reshape((2, 2)) elif num_vars == 1: A = np.array(coeffs).reshape((1, 1)) else: print("Error: The system of equations should contain either one or two variables.") return B = np.array(constants) # Solve the system of equations try: solution = np.linalg.solve(A, B) # Print the solution print(f"x0 = {solution[0]}") if num_vars == 2: print(f"x1 = {solution[1]}") except np.linalg.LinAlgError as e: print("Error: The system of equations is either inconsistent or cannot be solved.") # Call the function to solve the equations solve_equations() # EXAMPLE # Enter equation 1 (use x0 and x1 as variables): 2*x0 + 3*x1 = 4 # Enter equation 2 (use x0 and x1 as variables): 5*x0 - x1 = 7
Run
You can execute any Python code. Just enter something in the box above and click the button.