Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»ai»Gaussian Elimination in Python
    ai

    Gaussian Elimination in Python

    April 1, 2023No Comments4 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Gaussian Elimination in Python

    The usage of linear and polynomial equations is prevalent across almost the entirety of the field of numerical simulation. However, its most obvious use can be found in the discipline of engineering that deals with the analysis of linear systems of equations. Linear systems are a broad category that includes many different subcategories, such as structures, elastic material, heat fluxes, electromagnetism, electrical circuits, and many more.

    When modeling linear systems, mathematical equations of the sort Ax = b are generated. In these equations, x represents the input matrix, and b represents the response vector for the system being modeled. Independent of the input vector, A, also known as the matrix of coefficients, contains a reflection of the fundamental attributes of the system. The linear equation system that we want to evaluate will still include the exact coefficients matrix A, but it will have a different response vector if the input is altered.

    b.

    Methods of Solving Systems of Linear Equations

    In addition to the iterative techniques, there are also so-called straightforward approaches, which we won’t go over here because they aren’t relevant to the topic at hand. Their common goal is to simplify the process of solving the source equations by converting them into a system that has the same features as the original system but is easier to solve.

    This can be accomplished through the use of three major procedures.

    transformation:

    • The numeric value of A’s determinant flips sign when two lines of the matrix A are swapped;
    • The numeric value of the determinant of A gets multiplied by the same scalar by which the row of the matrix A is multiplied;
    • A’s determinant is left unaltered if we change a row of A by the one produced by appending that row to some other row scaled by a scalar;

    These processes, of course, have no influence on the system’s solutions, which remain unaltered; but, they might have an impact on the coefficient matrix A and the determinant of that matrix.

    The following is a compilation of the three most important direct routes to potential solutions.

    table:

    Method Initial form Final form

    Gauss elimination
    Ax = b Ux = c

    LU decomposition
    Ax = b LUx = b

    Gauss-Jordan elimination
    Ax = b Ix = c

    Gauss Elimination Method

    Row reduction is another name for the statistical technique known as Gaussian elimination. A linear system of equations can be solved using this technique, which is based on linear algebra. A coefficients matrix goes through a number of processes, which are the heart of what happens. These are the activities that are being carried out.

    involved:

    1. We can swap two rows
    2. Scaling a row by multiplying it with a scaler
    3. Adding a row to another row of the matrix

    These steps are carried out for as long as is required to ensure that the lower left side of the coefficient matrix is filled with

    zeros.

    Gauss Elimination Algorithm in Python

    In terms of the manual process, there are two alternative ways: the first is that the rows are converted by subtracting rather than by adding, and the second is that the converted rows are not substituted by the beginning rows of the matrix A, but rather by the components that are unique to an upper triangular matrix. Both of these techniques involve changing the way that the rows are converted. In point of fact, the computation of solutions is not in any way impacted by components that are not part of U. (the modified matrix). Code



    1. # Python program to find a solution to a set of linear equations using the Gaussian Elimination method






    2. # Creating a function to print the augmented matrix with the given set of linear equations





    3. def


      print_aug(mat):


    4. no = len(mat)


    5. for


      i


      in


      range(


      0


      , no):


    6. l = “”


    7. for


      k


      in


      range(


      0


      , n +


      1


      ):


    8. l += str(mat[i][k]) +

      “\t”





    9. if


      j == no –


      1


      :


    10. l +=

      “| ”





    11. print


      (l)



    12. print


      (“”)




    13. # Creating a function to perform gaussian elimination on the given matrix mat





    14. def


      gauss_elem(mat):


    15. num = len(mat)



    16. for


      i


      in


      range(


      0


      , num):



    17. # Searching the maximum value of a particular column




    18. max_el = abs(mat[i][i])


    19. # Row having the element of maximum value




    20. max_row = i


    21. for


      k


      in


      range(i +


      1


      , num):



    22. if


      abs(mat[k][i]) > max_el:


    23. max_el = abs(mat[k][i])

    24. max_row = k



    25. # Swapping the maximum row with the current row





    26. for


      k


      in


      range(i, n +


      1


      ):


    27. temp = mat[max_row][k]

    28. mat[max_row][k] = mat[i][k]

    29. mat[i][k] = temp



    30. # Chaning the value of the rows below the current row to 0





    31. for


      k


      in


      range(i +


      1


      , n):


    32. curr = -mat[k][i] / mat[i][i]


    33. for


      j


      in


      range(i, n +


      1


      ):



    34. if


      i == j:


    35. mat[k][j] =

      0





    36. else


      :


    37. mat[k][j] += curr * mat[i][j]



    38. # Solving the equation Ax = b for the created upper triangular matrix mat




    39. l = [

      0




      for


      i


      in


      range(n)]



    40. for


      j


      in


      range(n –


      1


      , –


      1


      , –


      1


      ):


    41. l[j] = mat[j][n] / mat[j][j]


    42. for


      k


      in


      range(j –


      1


      , –


      1


      , –


      1


      ):


    43. mat[k][n] -= mat[k][j] * l[j]


    44. return


      l





    45. if


      __name__ ==


      “__main__”


      :



    46. from


      fractions


      import


      Fraction



    47. n = int(input())


    48. A_mat = [[

      0




      for


      j


      in


      range(n +


      1


      )]


      for


      i


      in


      range(n)]




    49. # Reading the input coefficients of the linear equations





    50. for


      j


      in


      range(


      0


      , n):


    51. l = map(Fraction, input().split(

      ” ”


      ))



    52. for


      i, elem


      in


      enumerate(l):


    53. A_mat[j][i] = elem



    54. l = input().split(

      ” ”


      )



    55. print


      (l)


    56. last = list(map(Fraction, l))


    57. for


      j


      in


      range(


      0


      , n):


    58. A_mat[j][n] = last[j]



    59. # Printing the augmented matrix from the input data




    60. print_aug(A_mat)



    61. # Calculating the solution of the matrix




    62. x = gauss_elem(A_mat)



    63. # Printing the result




    64. l =

      “Result:\t”





    65. for


      j


      in


      range(


      0


      , n):


    66. l += str(x[j]) +

      “\t”





    67. print


      (l)

    Output:

    3
    3 4 -1
    5 -2 1
    2 -2 1
    8 4 1
    ['8', '4', '1']
    3

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous Articlegetitem in Python
    Next Article Custom Python Dictionaries Inheriting From dict vs UserDict

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.