
177 views
Gaussian Elimination in Python
Gaussian elimination is a method for solving systems of linear equations by transforming the system’s augmented matrix into row-echelon form (or reduced row-echelon form). You can implement Gaussian elimination in Python using NumPy, a powerful library for numerical computations. Here’s a step-by-step guide on how to perform Gaussian elimination in Python:
- Install NumPy if you haven’t already:
Bash
pip install numpy
- Implement Gaussian elimination:
Python
import numpy as np
def gaussian_elimination(A, b):
# Augment the coefficient matrix A with the column vector b
augmented_matrix = np.column_stack((A, b))
# Get the number of rows and columns in the augmented matrix
num_rows, num_cols = augmented_matrix.shape
# Perform Gaussian elimination
for col in range(num_cols - 1): # Exclude the last column (b)
# Find the pivot row (the row with the largest absolute value in the current column)
pivot_row = np.argmax(np.abs(augmented_matrix[col:, col])) + col
# Swap the current row with the pivot row
augmented_matrix[[col, pivot_row]] = augmented_matrix[[pivot_row, col]]
# Make the diagonal element of the current row equal to 1
augmented_matrix[col] = augmented_matrix[col] / augmented_matrix[col, col]
# Eliminate the non-zero values below the current row
for row in range(col + 1, num_rows):
factor = augmented_matrix[row, col]
augmented_matrix[row] = augmented_matrix[row] - factor * augmented_matrix[col]
# Back-substitution to find the solution
x = np.zeros(num_cols - 1)
for row in range(num_rows - 1, -1, -1):
x[row] = augmented_matrix[row, -1] - np.dot(augmented_matrix[row, row+1:num_cols-1], x)
return x
# Example usage:
A = np.array([[2, 1, -1],
[1, 3, 2],
[3, 2, 0]], dtype=float)
b = np.array([8, 11, 6], dtype=float)
solution = gaussian_elimination(A, b)
print("Solution:", solution)
In this code:
gaussian_elimination
is a function that takes a coefficient matrixA
and a column vectorb
as inputs and returns the solution vectorx
.- The function augments the coefficient matrix with the column vector
b
to create an augmented matrix. - It performs Gaussian elimination to transform the augmented matrix into row-echelon form.
- After row-echelon form is achieved, the code performs back-substitution to find the solution vector
x
. - Finally, it prints the solution vector.
You can replace the example A
and b
with your own coefficient matrix and column vector to solve your specific system of linear equations.