1. 顺序高斯消去法(Gaussian Elimination)
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)代码说明
示例
注意事项
Last updated