How to solve a system of linear equations using Numpy?

              System of linear equations have a set of equations with same variable. It has a solution of values which suits all the equations.

It can be done by input validation, error handling. Let us create a python program to solve this.

Code:

import numpy as np

def solveIt_linear_system():

    try:

        # Input statement

        n = int(input("Enter the number of equations/variables: "))

        if n <= 0:

            print("Number of equations must be positive.")

            return

        # Read the coefficient matrix

        print(f"Enter the {n}x{n} coefficient matrix (row by row):")

        coeff_matrix = []

        for i in range(n):

            row = input(f"Row {i+1} (space-separated numbers): ").strip().split()

            if len(row) != n:

                print("Invalid row length. Must match number of variables.")

                return

            coeff_matrix.append([float(x) for x in row])

        # Read the constants vector

        print(f"Enter the {n}-element constants vector:")

        constants = input("Space-separated numbers: ").strip().split()

        if len(constants) != n:

            print("Invalid constants length. Must match number of variables.")

            return

        constants = [float(x) for x in constants]

        # Convert the value  into NumPy arrays

        A = np.array(coeff_matrix, dtype=float)

        b = np.array(constants, dtype=float)

        # Solution

        try:

            solution = np.linalg.solve(A, b)

            print("\nSolution:")

            for i, val in enumerate(solution, start=1):

                print(f"x{i} = {val:.4f}")

        except np.linalg.LinAlgError as e:

            print(f"Error solving system: {e}")

    except ValueError:

        print("Invalid input. Please enter numeric values only.")

if __name__ == "__main__":

    solveIt_linear_system()

Output:

Enter the number of equations/variables: 3

Enter the 3x3 coefficient matrix (row by row):

Row 1 (space-separated numbers): 2 3 4

Row 2 (space-separated numbers): 5 6 7

Row 3 (space-separated numbers): 8 9 1

Enter the 3-element constants vector:

Space-separated numbers: 12 -4 -8

Solution:

x1 = -29.3333

x2 = 25.3333

x3 = -1.3333

Hope, you understood the code. This is the way to solve the system of linear equations in python. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Java script – conditional statement