Python 矩阵乘法,求解 Ax = b 求解 x

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22163113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:24:05  来源:igfitidea点击:

Matrix multiplication, solve Ax = b solve for x

pythonnumpymatrix-multiplication

提问by Scalahansolo

So I was given a homework assignment that requires solving the coefficients of cubic splines. Now I clearly understand how to do the math on paper as well as with MatLab, I want to solve the problem with Python. Given an equation Ax = b where I know the values of A and b, I want to be able to solve for x with Python and I am having trouble finding a good resource to do such a thing.

所以我得到了一个家庭作业,要求求解三次样条的系数。现在我清楚地了解如何在纸上以及使用 MatLab 进行数学运算,我想用 Python 解决这个问题。给定一个方程 Ax = b,其中我知道 A 和 b 的值,我希望能够用 Python 求解 x,但我很难找到一个好的资源来做这样的事情。

Ex.

前任。

A = |1 0 0|
    |1 4 1|
    |0 0 1|

x = Unknown 3x1 matrix

b = |0 |
    |24| 
    |0 |

Solve for x

求解 x

采纳答案by ev-br

In a general case, use solve:

在一般情况下,使用solve

>>> import numpy as np
>>> from scipy.linalg import solve
>>> 
>>> A = np.random.random((3, 3))
>>> b = np.random.random(3)
>>> 
>>> x = solve(A, b)
>>> x
array([ 0.98323512,  0.0205734 ,  0.06424613])
>>> 
>>> np.dot(A, x) - b
array([ 0.,  0.,  0.])

If your problem is banded (which cubic splines it often are), then there's http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html

如果您的问题是带状的(通常是三次样条),那么http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html

To comment on some of the comments to the question: better notuse invfor solving linear systems. numpy.lstsqis a bit different, it's more useful for fitting.

对一些评论的问题的意见:最好使用inv求解线性系统。numpy.lstsq有点不同,它对拟合更有用。

As this is homework, you're really better off at least reading up on ways of solving tridiagonal linear systems.

由于这是家庭作业,因此您最好至少阅读解决三对角线性系统的方法。

回答by BushMinusZero

Numpy is the main package for scientific computing in Python. If you are windows user then download it here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpyelse follow these instructions: http://www.scipy.org/install.html.

Numpy 是 Python 科学计算的主要包。如果您是 Windows 用户,请在此处下载:http: //www.lfd.uci.edu/~gohlke/pythonlibs/#numpy否则请按照以下说明进行操作:http: //www.scipy.org/install.html

import numpy
A = [[1,0,0],[1,4,1],[0,0,1]]
b = [0,24,0]
x = numpy.linalg.lstsq(A,b)

回答by moldovean

In addition to the code of Zhenya, you might also find it intuitive to use the np.dot function:

除了Zhenya的代码,你可能还会发现使用np.dot函数很直观:

import numpy as np
A = [[1,0,0],
    [1,1,1],
    [6,7,0]]
b = [0,24,0]
# Now simply solve for x
x = np.dot(np.linalg.inv(A), b) 
#np.linalg.inv(A)  is simply the inverse of A, np.dot is the dot product
print x

Out[27]: array([  0.,   0.,  24.])