跳转至

线性代数(三)线性方程组

章节概述

线性方程组是线性代数的核心问题之一,是解决实际问题的重要数学工具。本章将介绍线性方程组的解法、解的结构以及应用。

学习目标

  • 理解线性方程组的表示方法
  • 掌握高斯消元法
  • 理解矩阵的秩与方程组解的关系
  • 掌握线性方程组解的结构
  • 了解线性方程组的应用

(一)线性方程组的表示

矩阵形式

n 元线性方程组可以表示为:

a₁₁x₁ + a₁₂x₂ + ... + a₁ₙxₙ = b₁
a₂₁x₁ + a₂₂x₂ + ... + a₂ₙxₙ = b₂
...
aₘ₁x₁ + aₘ₂x₂ + ... + aₘₙxₙ = bₘ

矩阵形式为:

Ax = b

其中: - A 是 m×n 系数矩阵 - x 是 n×1 未知向量 - b 是 m×1 常数向量

增广矩阵

增广矩阵 [A|b] 是在系数矩阵 A 后加上常数向量 b:

[A|b] = |a₁₁ a₁₂ ... a₁ₙ b₁|
        |a₂₁ a₂₂ ... a₂ₙ b₂|
        |...                  |
        |aₘ₁ aₘ₂ ... aₘₙ bₘ|

Python 实现

def augmented_matrix(A, b):
    """
    创建增广矩阵

    参数:
        A: 系数矩阵 (m×n)
        b: 常数向量 (n×1)

    返回:
        list: 增广矩阵

    示例:
        >>> A = [[1, 2], [3, 4]]
        >>> b = [5, 6]
        >>> augmented_matrix(A, b)
        [[1, 2, 5], [3, 4, 6]]
    """
    m = len(A)
    n = len(A[0])
    result = []

    for i in range(m):
        row = A[i].copy()
        row.append(b[i])
        result.append(row)

    return result

def print_equation_system(A, b):
    """
    打印线性方程组

    参数:
        A: 系数矩阵
        b: 常数向量
    """
    m = len(A)
    n = len(A[0])

    for i in range(m):
        equation = ""
        for j in range(n):
            if j > 0:
                equation += " + "
            equation += f"{A[i][j]}x{j+1}"
        equation += f" = {b[i]}"
        print(equation)

实例分析

实例1:创建增广矩阵

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
b = [10, 11, 12]

Aug = augmented_matrix(A, b)
print("增广矩阵:")
for row in Aug:
    print(row)

实例2:打印线性方程组

A = [[2, 1],
     [1, -1]]
b = [3, 0]

print("线性方程组:")
print_equation_system(A, b)
# 输出:
# 2x1 + 1x2 = 3
# 1x1 + -1x2 = 0

(二)高斯消元法

基本思想

高斯消元法通过初等行变换将增广矩阵化为行阶梯形,然后回代求解。

初等行变换

  1. 交换两行
  2. 某行乘以非零常数
  3. 某行的倍数加到另一行

行阶梯形矩阵

满足以下条件的矩阵: 1. 每个非零行的第一个非零元素(主元)的列号比上一行的主元列号大 2. 全零行在矩阵的底部

Python 实现

def gauss_elimination(A, b, tolerance=1e-10):
    """
    高斯消元法解线性方程组

    参数:
        A: 系数矩阵 (n×n)
        b: 常数向量 (n×1)
        tolerance: 容差

    返回:
        list: 解向量,无解或有无穷多解时返回 None

    示例:
        >>> A = [[2, 1], [1, -1]]
        >>> b = [3, 0]
        >>> gauss_elimination(A, b)
        [1.0, 1.0]
    """
    import copy
    n = len(A)
    Aug = augmented_matrix(A, b)

    # 前向消元
    for i in range(n):
        # 寻找主元
        max_row = i
        for k in range(i + 1, n):
            if abs(Aug[k][i]) > abs(Aug[max_row][i]):
                max_row = k

        # 交换行
        if max_row != i:
            Aug[i], Aug[max_row] = Aug[max_row], Aug[i]

        # 检查主元是否为零
        if abs(Aug[i][i]) < tolerance:
            return None  # 无解或有无穷多解

        # 消元
        for k in range(i + 1, n):
            factor = Aug[k][i] / Aug[i][i]
            for j in range(i, n + 1):
                Aug[k][j] -= factor * Aug[i][j]

    # 回代
    x = [0] * n
    for i in range(n - 1, -1, -1):
        x[i] = Aug[i][n] / Aug[i][i]
        for j in range(i + 1, n):
            x[i] -= Aug[i][j] * x[j] / Aug[i][i]

    return x

def gauss_jordan(A, b, tolerance=1e-10):
    """
    高斯-若尔当消元法

    参数:
        A: 系数矩阵 (n×n)
        b: 常数向量 (n×1)
        tolerance: 容差

    返回:
        list: 解向量

    示例:
        >>> A = [[2, 1], [1, -1]]
        >>> b = [3, 0]
        >>> gauss_jordan(A, b)
        [1.0, 1.0]
    """
    import copy
    n = len(A)
    Aug = augmented_matrix(A, b)

    # 前向消元
    for i in range(n):
        # 寻找主元
        max_row = i
        for k in range(i + 1, n):
            if abs(Aug[k][i]) > abs(Aug[max_row][i]):
                max_row = k

        # 交换行
        if max_row != i:
            Aug[i], Aug[max_row] = Aug[max_row], Aug[i]

        # 检查主元是否为零
        if abs(Aug[i][i]) < tolerance:
            return None

        # 消元(包括上面和下面的行)
        for k in range(n):
            if k != i:
                factor = Aug[k][i] / Aug[i][i]
                for j in range(i, n + 1):
                    Aug[k][j] -= factor * Aug[i][j]

    # 提取解
    x = [Aug[i][n] / Aug[i][i] for i in range(n)]
    return x

实例分析

实例1:高斯消元法

A = [[2, 1],
     [1, -1]]
b = [3, 0]

x = gauss_elimination(A, b)
print(f"解: x = {x}")  # 输出: [1.0, 1.0]

实例2:高斯-若尔当消元法

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 10]]
b = [6, 15, 23]

x = gauss_jordan(A, b)
print(f"解: x = {x}")  # 输出: [1.0, 1.0, 1.0]

(三)解的结构

解的存在性和唯一性

对于 n 元线性方程组 Ax = b:

情况1:唯一解 - rank(A) = rank([A|b]) = n

情况2:无解 - rank(A) < rank([A|b])

情况3:有无穷多解 - rank(A) = rank([A|b]) < n

齐次线性方程组

齐次线性方程组 Ax = 0 总是有解(零解)。

定理:齐次线性方程组有非零解的充分必要条件是 rank(A) < n

非齐次线性方程组

非齐次线性方程组 Ax = b 的通解为:

x = x₀ + Σ(cᵢ·ξᵢ)

其中: - x₀ 是特解 - ξᵢ 是对应齐次方程组的基础解系 - cᵢ 是任意常数

Python 实现

def solution_structure(A, b, tolerance=1e-10):
    """
    分析线性方程组的解的结构

    参数:
        A: 系数矩阵 (m×n)
        b: 常数向量 (m×1)
        tolerance: 容差

    返回:
        dict: 解的结构信息
    """
    import numpy as np
    A_np = np.array(A, dtype=float)
    b_np = np.array(b, dtype=float)

    # 计算系数矩阵和增广矩阵的秩
    rank_A = np.linalg.matrix_rank(A_np, tol=tolerance)
    rank_Aug = np.linalg.matrix_rank(np.column_stack((A_np, b_np)), tol=tolerance)

    n = len(A[0])

    if rank_A < rank_Aug:
        return {
            "type": "无解",
            "rank_A": rank_A,
            "rank_Aug": rank_Aug
        }
    elif rank_A == n:
        # 唯一解
        x = np.linalg.solve(A_np, b_np)
        return {
            "type": "唯一解",
            "solution": x.tolist(),
            "rank_A": rank_A,
            "rank_Aug": rank_Aug
        }
    else:
        # 无穷多解
        return {
            "type": "无穷多解",
            "free_variables": n - rank_A,
            "rank_A": rank_A,
            "rank_Aug": rank_Aug
        }

def solve_homogeneous(A, tolerance=1e-10):
    """
    解齐次线性方程组 Ax = 0

    参数:
        A: 系数矩阵 (m×n)
        tolerance: 容差

    返回:
        list: 基础解系
    """
    import numpy as np
    A_np = np.array(A, dtype=float)

    rank = np.linalg.matrix_rank(A_np, tol=tolerance)
    n = len(A[0])

    if rank == n:
        return []  # 只有零解

    # 使用 SVD 计算零空间
    U, s, Vh = np.linalg.svd(A_np)
    null_space = Vh[rank:].T

    return null_space.tolist()

实例分析

实例1:唯一解

A = [[2, 1],
     [1, -1]]
b = [3, 0]

result = solution_structure(A, b)
print(f"解的类型: {result['type']}")
print(f"解: {result['solution']}")

实例2:无解

A = [[1, 1],
     [1, 1]]
b = [1, 2]

result = solution_structure(A, b)
print(f"解的类型: {result['type']}")

实例3:无穷多解

A = [[1, 1, 1],
     [1, 1, 1],
     [1, 1, 1]]
b = [1, 1, 1]

result = solution_structure(A, b)
print(f"解的类型: {result['type']}")
print(f"自由变量个数: {result['free_variables']}")

(四)线性方程组的应用

1. 网络流问题

描述网络中各节点的流量平衡。

def network_flow(nodes, edges, sources, sinks):
    """
    网络流问题

    参数:
        nodes: 节点列表
        edges: 边列表 [(from, to, capacity), ...]
        sources: 源节点及其流量 [(node, flow), ...]
        sinks: 汇节点及其流量 [(node, flow), ...]

    返回:
        dict: 各边的流量
    """
    import numpy as np

    # 构建流量平衡方程
    n = len(edges)
    m = len(nodes)

    A = [[0] * n for _ in range(m - 1)]
    b = [0] * (m - 1)

    # 填充系数矩阵
    for i, edge in enumerate(edges):
        from_node, to_node, capacity = edge
        if from_node != m - 1:  # 不包括最后一个节点(平衡方程)
            A[from_node][i] = -1
        if to_node != m - 1:
            A[to_node][i] = 1

    # 填充常数向量
    for node, flow in sources:
        if node != m - 1:
            b[node] += flow
    for node, flow in sinks:
        if node != m - 1:
            b[node] -= flow

    # 解方程组
    x = np.linalg.lstsq(np.array(A), np.array(b), rcond=None)[0]

    return {f"{edge[0]}->{edge[1]}": x[i] for i, edge in enumerate(edges)}

2. 最小二乘拟合

用线性方程组求解拟合曲线的参数。

def least_squares_fit(points, degree=1):
    """
    最小二乘拟合

    参数:
        points: 数据点列表 [(x, y), ...]
        degree: 多项式次数

    返回:
        list: 拟合系数
    """
    import numpy as np

    # 构建设计矩阵
    X = []
    y = []
    for x_val, y_val in points:
        row = [x_val ** i for i in range(degree + 1)]
        X.append(row)
        y.append(y_val)

    # 解正规方程组: (X^T X) β = X^T y
    X_np = np.array(X, dtype=float)
    y_np = np.array(y, dtype=float)

    # 添加 Tikhonov 正则化以避免数值不稳定
    regularization = 1e-10
    beta = np.linalg.solve(X_np.T @ X_np + regularization * np.eye(degree + 1),
                          X_np.T @ y_np)

    return beta.tolist()

# 示例:线性拟合
points = [(1, 2), (2, 3), (3, 5), (4, 4), (5, 5)]
coefficients = least_squares_fit(points, degree=1)
print(f"拟合系数: {coefficients}")  # [b, a] 对应 y = a*x + b

3. 资源分配

求解资源的最优分配方案。

def resource_allocation(resources, demands):
    """
    资源分配问题

    参数:
        resources: 可用资源数量
        demands: 各项目需求 [(project, demand), ...]

    返回:
        list: 分配方案
    """
    import numpy as np

    # 构建约束矩阵
    n = len(demands)
    A = np.ones((1, n))
    b = np.array([resources])

    # 目标函数(最小化总需求不满足)
    c = np.ones(n)

    # 简化:按比例分配
    total_demand = sum(demand for _, demand in demands)
    allocation = [(project, (demand / total_demand) * resources)
                  for project, demand in demands]

    return allocation

实战练习

练习1:高斯消元法

使用高斯消元法解下列方程组:

x + y + z = 6
2x - y + z = 3
x + 2y - z = 2

A = [[1, 1, 1],
     [2, -1, 1],
     [1, 2, -1]]
b = [6, 3, 2]

x = gauss_elimination(A, b)
print(f"解: x = {x}")  # [1.0, 2.0, 3.0]

练习2:解的结构

分析下列方程组的解的结构:

x + y + z = 1
2x + 2y + 2z = 2
3x + 3y + 3z = 3

A = [[1, 1, 1],
     [2, 2, 2],
     [3, 3, 3]]
b = [1, 2, 3]

result = solution_structure(A, b)
print(f"解的类型: {result['type']}")
print(f"自由变量个数: {result['free_variables']}")

练习3:最小二乘拟合

对下列数据进行线性拟合:

points = [(0, 1), (1, 3), (2, 2), (3, 5), (4, 4)]
coefficients = least_squares_fit(points, degree=1)
print(f"拟合直线: y = {coefficients[1]:.2f}x + {coefficients[0]:.2f}")

章节小结

本章介绍了线性方程组:

  1. 线性方程组的表示:理解矩阵形式和增广矩阵
  2. 高斯消元法:掌握高斯消元法和高斯-若尔当消元法
  3. 解的结构:理解解的存在性、唯一性和通解结构
  4. 线性方程组的应用:了解在网络流、拟合、资源分配中的应用

线性方程组是线性代数的核心,广泛应用于科学计算、工程技术和数据分析等领域。

下一步

继续学习第四章:向量空间,学习向量空间的概念、基、维数等内容。


重点提醒: - 高斯消元法是解线性方程组的基本方法 - 矩阵的秩决定了解的结构 - 齐次方程组总有零解 - 非齐次方程组的通解 = 特解 + 齐次方程组的通解 - 最小二乘法用于求解无解方程组的最优解