在Python中解决线性方程组AX = B,np.linalg.solve无法正常工作 [英] Solve the linear equations system AX = B in Python, np.linalg.solve not working

查看:96
本文介绍了在Python中解决线性方程组AX = B,np.linalg.solve无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试求解线性方程AX = B,其中A,X,B是矩阵.
我尝试使用 numpy np.linalg.solve 函数,但是结果似乎是错误的.
示例:

I'm trying to solve the linear equation AX=B where A,X,B are Matrices.
I've tried using the np.linalg.solve function of numpy but the result seems to be wrong.
Example:

Matrix A  
[9 1 8]  
[3 2 5]  
[1 6 5]  

Matrix B  
[7 0 5]  
[7 8 4]  
[5 6 7]  

所以要解决X,我用过:

So to solve X, i've used:

X = np.linalg.solve(A,B)

结果是:

X  
[ 1.17521368 -0.17948718  0.40598291]  
[ 0.20512821 -0.30769231  0.74358974]  
[-0.56410256 -0.15384615  1.20512821]  

但是,如果我尝试通过将A乘以X来验证结果,则结果除B之外都不会:

But if i try to verify the result by multiplying A by X, the result is anything but B:

B
[ 5.40598291 -2.02564103  8.86752137]  
[ 7.61111111 -4.33333333 13.61111111]  
[ 3.15811966 -3.82051282 14.92735043]  

如果我使用这个:

np.matmul(B, np.linalg.inv(A))

我得到的结果不是求解函数,而是相同的结果.

Instead of the solve function, i get the same results.

我这里缺少什么吗?

我已经打印

np.allclose(np.dot(A, X), B)

并且返回 False

编辑2
这是我正在使用的代码:

EDIT 2
Here is the code i'm using:

B = np.array([7,0,5,7,8,4,5,6,7]).reshape(3,3)
A = np.array([9,1,8,3,2,5,1,6,5]).reshape(3,3)
X = np.linalg.solve(A,B)
print(x)
#[[-1.70967742 -4.48387097  0.08064516]
# [-1.35483871 -2.74193548  0.79032258]
# [ 2.96774194  5.38709677  0.43548387]]

如果这是一个非常基本的问题,我深表歉意,感谢您的帮助.谢谢.

My apologies if this is a very basic question, i appreciate any help. Thanks.

推荐答案

我的数组结果正确:

In [582]: A=np.array([9,1,8,3,2,5,1,6,5]).reshape(3,3)                                                
In [583]: B=np.array([7,0,5,7,8,4,5,6,7]).reshape(3,3)                                                
In [584]: x=np.linalg.solve(A,B)                                                                      
In [585]: x                                                                                           
Out[585]: 
array([[-1.70967742, -4.48387097,  0.08064516],
       [-1.35483871, -2.74193548,  0.79032258],
       [ 2.96774194,  5.38709677,  0.43548387]])
In [586]: A@x                                                                                         
Out[586]: 
array([[7., 0., 5.],
       [7., 8., 4.],
       [5., 6., 7.]])

另一种方法: AX = B => X = 1/A B :

The other approach: AX=B => X=1/A B:

In [591]: np.linalg.inv(A)@B                                                                          
Out[591]: 
array([[-1.70967742, -4.48387097,  0.08064516],
       [-1.35483871, -2.74193548,  0.79032258],
       [ 2.96774194,  5.38709677,  0.43548387]])

并正式测试是否相等:

In [602]: np.allclose(A@np.linalg.solve(A, B), B)                                                       
Out[602]: True

这篇关于在Python中解决线性方程组AX = B,np.linalg.solve无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆