简体   繁体   English

python上的线性代数

[英]Linear algebra on python

i would like to use numpy.linalg.solve to solve a linear algebra equation, but i got an error message saying 'Last 2 dimensions of the array must be square'. 我想使用numpy.linalg.solve来解决线性代数方程,但我得到一条错误消息,说“数组的最后2个维度必须是正方形”。 Please shed some light thanks a lot !! 非常感谢!! here's my code: 这是我的代码:

import numpy as np
from numpy. linalg import solve

A = np.array([[3,-1,-1,0,0,0], [-1,4,-1,-1,0,0], [0,0,-1,-1,4,-1], [0,0,0,-1,-1,3]],float)

w = np.array([5,5,0,0],float)

v = solve(A,w)

print(v)

As igavriil already wrote numpy.linalg.solve can only be used to find (the exact) solution for a well-determined system (ie sqare coefficient matrix). 由于igavriil已经写过numpy.linalg.solve只能用于找到一个确定系统的(确切的)解决方案(即sqare系数矩阵)。 If your system is under- or over-determined, there is usually no exact solution. 如果您的系统不足或过度确定,通常没有确切的解决方案。

If you want to find an approximate solution, you can use numpy.linalg.lstsq . 如果要查找近似解,可以使用numpy.linalg.lstsq It uses a method called "least-squares-fitting" to find a solution that minimizes the overall error. 它使用一种称为“最小二乘拟合”的方法来找到最小化整体误差的解决方案。

What this error basically says is that the linear system cannot be solved explicitly. 这个错误基本上说的是线性系统无法明确解决。 This is because you have 6 variables and only 4 equations. 这是因为你有6个变量,只有4个方程式。 In other words the coefficient matrix must be a square matrix. 换句话说,系数矩阵必须是方阵。 The error is raised when: 在以下情况下引发错误:

max(a.shape[-2:]) != min(a.shape[-2:]):

So if you want A x = b and A is not square, you can simply do: 所以,如果你想要A x = b而A不是正方形,你可以简单地做:

A_pseudoinverse = np.linalg.pinv(A)
x = A_pseudoinverse @ b

It's the same as @jandjob's answer, or at least close enough. 它与@ jandjob的回答相同,或者至少足够接近。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM