import numpy as np
def gaussian_elimination(A, b):
"""
Solve the system of linear equations Ax = b using Gaussian Elimination.
Parameters:
A : 2D list or numpy array
Coefficient matrix
b : 1D list or numpy array
Right-hand side vector
Returns:
x : numpy array
Solution vector
"""
n = len(b)
# Forward elimination
for i in range(n):
# Make the diagonal contain all 1's
A[i] = [a / A[i][i] for a in A[i]]
b[i] /= A[i][i]
# Make the elements below the pivot positions zero
for j in range(i+1, n):
factor = A[j][i]
A[j] = [a_j - factor * a_i for a_j, a_i in zip(A[j], A[i])]
b[j] -= factor * b[i]
# Backward substitution
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = b[i] - sum(a_ij * x_j for a_ij, x_j in zip(A[i][i+1:], x[i+1:]))
return x
# Example usage
A = [[2, -1, 1],
[3, 3, 9],
[3, 3, 5]]
b = [2, -1, 2]
A = np.array(A, dtype=float)
b = np.array(b, dtype=float)
x = gaussian_elimination(A, b)
print("Solution:", x)
代码说明
输入参数:
A:系数矩阵,可以是二维列表或NumPy数组。
b:右端向量,可以是一维列表或NumPy数组。
前向消去(Forward Elimination):
遍历每一行,将主元归一化。
使用当前行的主元,将该行下面所有行的对应列元素消去。
回代(Backward Substitution):
从最后一行开始,逐步向上回代,求解每一个未知数。
示例
给定系数矩阵 (A) 和右端向量 (b):
A = [[2, -1, 1],
[3, 3, 9],
[3, 3, 5]]
b = [2, -1, 2]