✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.
The following code implements Gaussian Elimination to solve Ax=b. What is the error?
import numpy as np
def gaussian_elimination(A, b):
n = len(b)
A = A.astype(float)
b = b.astype(float)
for k in range(n):
# Partial pivoting
max_row = np.argmax(np.abs(A[k:, k])) + k
A[[k, max_row]] = A[[max_row, k]]
b[[k, max_row]] = b[[max_row, k]]
# Elimination
for i in range(k+1, n):
factor = A[i, k] / A[k, k]
A[i, k:] -= factor * A[k, k:]
b[i] -= factor * b[k]
# Back substitution
x = np.zeros(n)
for k in range(n-1, -1, -1):
x[k] = (b[k] - np.dot(A[k, k+1:], x[k+1:])) / A[k, k]
return x
# Test case
A = np.array([[2, 1, -1], [4, 1, 0], [1, -1, 1]])
b = np.array([1, -2, 3])
print(gaussian_elimination(A, b))