Python code to solve linear algebra equation using Gaussian Elimination
Linear algebra equations involve systems of linear equations and matrices. To solve a system of linear equations, you can use Gaussian elimination, matrix inversion, or other methods.
Here is a Python function to solve a system of linear algebra equations using Gaussian elimination:
import numpy as np
def gaussian_elimination(A, b):
"""Solves the linear algebra equation Ax = b, where A is a matrix and b is a vector."""
n = len(b)
for i in range(n):
# Find the maximum value in the current column
max_index = np.argmax(np.abs(A[i:, i])) + i
# Swap the current row with the row containing the maximum value
A[[i, max_index]] = A[[max_index, i]]
b[[i, max_index]] = b[[max_index, i]]
# Eliminate the values in the current column below the current row
for j in range(i+1, n):
factor = A[j, i] / A[i, i]
A[j, i:] -= factor * A[i, i:]
b[j] -= factor * b[i]
# Solve the upper triangular system using back substitution
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (b[i] - np.dot(A[i, i+1:], x[i+1:])) / A[i, i]
return x
In this example, A is a matrix and b is a vector that represents the right-hand side of the equation Ax = b. The function gaussian_elimination performs Gaussian elimination on the matrix A and the vector b, and returns the solution vector x.
Note: This code assumes that you have the NumPy library installed in your environment.
Here’s an example of using the gaussian_elimination function and printing its output:
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([1, 2, 3])
x = gaussian_elimination(A, b)
print("The solution is:")
print(x)
This will produce the following output:
The solution is:
[-1.00000000e+00 1.00000000e+00 -5.55111512e-17]
In this example, the matrix A and the vector b represent the system of linear equations Ax = b. The function gaussian_elimination finds the solution x to the system of equations. The solution is printed.