2. 列主元高斯消去法(Gaussian Elimination with Partial Pivoting)
import numpy as np
def gaussian_elimination_with_partial_pivoting(A, b):
"""
Solve the system of linear equations Ax = b using Gaussian Elimination with Partial Pivoting.
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)
A = A.astype(float) # Ensure the matrix is of type float
b = b.astype(float) # Ensure the vector is of type float
# Forward elimination with partial pivoting
for i in range(n):
# Pivoting: find the row with the largest element in the current column
max_row_index = np.argmax(np.abs(A[i:n, i])) + i
if A[max_row_index, i] == 0:
raise ValueError("Matrix is singular or nearly singular")
# Swap the current row with the max_row_index row
A[[i, max_row_index]] = A[[max_row_index, i]]
b[[i, max_row_index]] = b[[max_row_index, i]]
# Make the diagonal element 1 and eliminate the column below
pivot = A[i, i]
A[i] = A[i] / pivot
b[i] = b[i] / pivot
for j in range(i + 1, n):
factor = A[j, i]
A[j] = A[j] - factor * A[i]
b[j] = b[j] - factor * b[i]
# Backward 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:])
return x
# Example usage
A = np.array([[2, -1, 1],
[3, 3, 9],
[3, 3, 5]], dtype=float)
b = np.array([2, -1, 2], dtype=float)
x = gaussian_elimination_with_partial_pivoting(A, b)
print("Solution:", x)代码说明
示例
注意事项
Last updated