You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Scipy求解含边界条件的欠定线性方程组问题

解决有限元法中带约束的欠定线性方程组问题

基础场景:固定解向量的部分分量

当你需要固定解向量的某些元素(比如强制x₀=0),可以通过拆分已知/未知分量,将原欠定方程组转化为适定方程组求解:

  1. 拆分解向量:将x分为固定值部分x_fixed(已知)和未知部分x_free
  2. 代入原方程A x = b,得到A x_free = b - A x_fixed
  3. 从原系数矩阵A中提取对应x_free的列,得到适定的子矩阵A_free
  4. 用scipy.linalg.solve求解A_free x_free = b_free,最后组装完整解

代码示例:

import numpy as np
from scipy.linalg import solve

# 原系数矩阵
A = np.array([
    [12., 6., -12., 6.],
    [6., 4., -6., 2.],
    [-12., -6., 12., -6.],
    [6., 2., -6., 4.]
])
# 右端项示例
b = np.array([0., 0., 0., 0.])

# 定义固定分量:索引0的值为0
fixed_indices = [0]
fixed_values = [0.]

# 筛选未知分量的索引
free_indices = [i for i in range(A.shape[1]) if i not in fixed_indices]

# 构建适定子矩阵和修正右端项
A_free = A[:, free_indices]
x_fixed = np.zeros(A.shape[1])
x_fixed[fixed_indices] = fixed_values
b_free = b - A @ x_fixed

# 求解并组装完整解
x_free = solve(A_free, b_free)
x = np.zeros_like(x_fixed)
x[fixed_indices] = fixed_values
x[free_indices] = x_free

print("解向量x:", x)

通用场景:含双未知向量+复合约束

如果右端项也包含未知变量(比如A x = B y + c),同时存在多组约束(比如x的固定分量、y的线性约束),可以通过合并未知变量将所有方程整合为标准线性方程组:

  1. 把所有未知变量合并为一个大向量z = [x; y]
  2. 将原方程和约束条件整理为M z = r的形式:
    • 原方程转化为A x - B y = c,对应增广矩阵的第一块
    • 每个约束条件(如F x = g、H y = k)对应增广矩阵的后续块
  3. 求解整合后的线性方程组

代码示例:

import numpy as np
from scipy.linalg import solve

# 原方程参数
A = np.array([
    [12., 6., -12., 6.],
    [6., 4., -6., 2.],
    [-12., -6., 12., -6.],
    [6., 2., -6., 4.]
])
B = np.array([[1., 0.], [0., 1.], [1., 0.], [0., 1.]])  # 右端项的y系数矩阵
c = np.array([1., 2., 3., 4.])

# 约束1:x的第0个分量为0
F = np.array([[1., 0., 0., 0.]])
g = np.array([0.])

# 约束2:y的两个分量之和为5
H = np.array([[1., 1.]])
k = np.array([5.])

# 构建增广矩阵M和右端项r
M_top = np.hstack([A, -B])
M_mid = np.hstack([F, np.zeros((F.shape[0], B.shape[1]))])
M_bot = np.hstack([np.zeros((H.shape[0], A.shape[1])), H])
M = np.vstack([M_top, M_mid, M_bot])

r = np.hstack([c, g, k])

# 求解拆分得到x和y
z = solve(M, r)
x = z[:A.shape[1]]
y = z[A.shape[1]:]

print("解向量x:", x)
print("解向量y:", y)

这种方法完全通用,不管约束数量、未知变量的组合形式,只要能转化为线性约束,都可以用这种方式整合求解。如果整合后的矩阵是方阵且可逆,scipy.linalg.solve可以直接求解;如果是超定但存在精确解,改用scipy.linalg.lstsq即可。

内容的提问来源于stack exchange,提问作者adgn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:15:34