Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

GAUSS ELIMINATION

METHOD

def gauss_elimination(A, b):
n = len(b)

# Augmented matrix
augmented_matrix = np.column_stack((A, b))

# Forward elimination
for pivot_row in range(n):
# Partial pivoting
max_row=max(range(pivot_row,n),key=lambda i:
abs(augmented_matrix[i, pivot_row]))
augmented_matrix[[pivot_row, max_row]] =
augmented_matrix[[max_row, pivot_row]]

# Elimination
for row in range(pivot_row + 1, n):
factor = augmented_matrix[row, pivot_row] /
augmented_matrix[pivot_row, pivot_row]
augmented_matrix[row, pivot_row:] -= factor *
augmented_matrix[pivot_row, pivot_row:]

# Back substitution
x = np.zeros(n)
for i in range(n - 1, -1, -1):
x[i] = (augmented_matrix[i, -1] - np.dot(augmented_matrix[i,
i+1:n], x[i+1:n])) / augmented_matrix[i, i]

return x

# Example usage
A = np.array([[2, 1, -1],
[-3, -1, 2],
[-2, 1, 2]])
b = np.array([8, -11, -3])

solution = gauss_elimination(A, b)
print("Solution:", solution)

You might also like