求解具有 3 个未知数的 2 个方程组

问题描述 投票:0回答:2

我必须求解这个三个未知数的方程组。

10x+5y+0.5z = 100
x+y+z = 100

在我的课程中,我被告知要使用

for
循环,但是,在我看来,这很困难。我想,我可以使用 numpy,但我的代码不正确。

import numpy as np

M1 = np.array([[10., 5., 0.5], [1., 1., 1.]])                        
v1 = np.array([100., 100.])

np.linalg.inv(M1).dot(v1)
python numpy linear-algebra
2个回答
3
投票

当求解方程数量少于变量的多变量线性方程时,这会变得很困难。这是因为解不是唯一的。这意味着同一组方程有多个答案。如果您的问题包含第三个方程,则求解该组方程的代码将如下所示:

import numpy as np

A = [[x1,y1,z1],[x2,y2,z2],[x3,y3,z3]] # Matrix of the coefficients of the left hand side of the equ.
B = [[d1],[d2],[d3]] # Where the d's represents the coefficients of the right hand side of the equ.
C = np.linalg.solve(A,B) # The order of the A,B matter.
#Also pay attention to the dimension of the matrices A = (3,3) , B = (3,1)
#If we had to swap the dimension of B = [d1,d2,d3] = (1,3) this calculation would 
#not work.

0
投票

这里遇到的是一个约束不足的问题,这意味着有无限多个解决方案,正如其他人所说。解决此类问题的一种选择是使用吉洪诺夫正则化,又名“岭回归”。您当前的问题是 Ax = b,其中

A
2x3
矩阵,
x
3x1
向量,
b
2x1
向量。 Tikhonov 正则化表示,您可以通过解决此问题来找到具有最小 2-范数的向量
x
(A'A - λI)x = A'b
,然后将极限设为
λ
变为 0。
这是在 sympy 中解决的问题。

import sympy as smp A = smp.Matrix([[10, 5, 0.5], [1, 1, 1]]) b = smp.Matrix([[100], [100]]) lamb = smp.symbols("\\lambda") x = (A.T@A - lamb*smp.eye(3)).solve(A.T@b).subs(lamb, 0) print(x) # Matrix([[-11.2546125461255], [34.8708487084871], [76.3837638376384]])

我们可以检查我们的解决方案是否有效。

print(A@x) # Matrix([[100.000000000000], [100.000000000000]])

© www.soinside.com 2019 - 2024. All rights reserved.