1. 顺序高斯消去法(Gaussian Elimination)

下面是使用Python实现顺序高斯消去法(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)

代码说明

  1. 输入参数

    • A:系数矩阵,可以是二维列表或NumPy数组。

    • b:右端向量,可以是一维列表或NumPy数组。

  2. 前向消去(Forward Elimination)

    • 遍历每一行,将主元归一化。

    • 使用当前行的主元,将该行下面所有行的对应列元素消去。

  3. 回代(Backward Substitution)

    • 从最后一行开始,逐步向上回代,求解每一个未知数。

示例

给定系数矩阵 (A) 和右端向量 (b):

A = [[2, -1, 1],
     [3, 3, 9],
     [3, 3, 5]]
b = [2, -1, 2]

运行上述代码,求解线性方程组 (Ax = b),可以得到解向量 x

注意事项

  • 该实现假设矩阵 (A) 是非奇异的,即有唯一解。

  • 由于直接除以主元来进行消去,该实现可能会遇到数值不稳定的问题。在实际应用中,可以考虑改进为列主元高斯消去法,以提高数值稳定性。

Last updated