为什么scipy.linalg.lu()在该代码中返回方阵B的错误分解矩阵?

2024-09-30 20:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码,其结果非常令人困惑:

import numpy as np
import scipy.linalg
B = np.array([[2,-1,-2],[-4,6,3],[-4,-2,8]])
P,L,U = scipy.linalg.lu(B)
print(L)

返回以下值:

[[ 1. 0. 0. ] [ 1. 1. 0. ] [-0.5 -0.25 1. ]]

但在B的LU分解中,这不是正确的L矩阵西皮·利纳格·卢(matrix)简单地计算你放入的任何矩阵的LU分解矩阵。然而,在这种情况下,L矩阵是不正确的。这是怎么回事?感谢任何帮助。在


Tags: 代码importnumpyasnp矩阵scipyarray
1条回答
网友
1楼 · 发布于 2024-09-30 20:20:04

我想你可能误解了分解应该做什么因为在我看来它是正确的。。。让我们浏览一下示例的结果,以及一些额外的细节和注释:

import numpy as np
import scipy.linalg
B = np.array([[2,-1,-2],[-4,6,3],[-4,-2,8]])
P,L,U = scipy.linalg.lu(B)  

# Now let's see if P is a permutation matrix (a single 1 in each row and column, all the rest should be zero):
print(P)  
>> [[ 0.  0.  1.]
   [ 1.  0.  0.]
   [ 0.  1.  0.]]
# Yup! That's a successful permutation matrix  

# Now let's see if L is a lower triangular matrix (anything above the main diagonal should be zero):
print(L)
>> [[ 1.    0.    0.  ]
   [ 1.    1.    0.  ]
   [-0.5  -0.25  1.  ]]
# Yup! still doing good.  

# Now let's see if U is a upper triangular matrix (anything below the main diagonal should be zero):
print(U)
>> [[-4.    6.    3.  ]
   [ 0.   -8.    5.  ]
   [ 0.    0.    0.75]]

# And last but not least, let's see if this works as a decomposition of B (i.e. PLU==B):  
print(np.matmul(P, np.matmul(L, U)))
>> [[ 2. -1. -2.]
   [-4.  6.  3.]
   [-4. -2.  8.]]

# :-)  

我希望这能澄清一些事情。如果你还不确定,那么也许可以重读关于permutation matricestriangular matriceslu-decompositionscipy.linalg.lu,以及密切相关的主题。
祝你好运!在


似乎已经做出了澄清:
LU分解在一般情况下并不一定是唯一的。
如果您想知道以上wikipedia链接中relevant sub-chapter的详细信息,我建议您先回答this堆栈交换问题。
因此,如果你碰巧从不同的实现或方法得到两个不同的答案,那并不意味着其中一个是错误的。如果你有一个置换矩阵P(即使它是平凡的单位矩阵),一个下矩阵L,一个上矩阵U,它们分解你的矩阵,那么你就得到了你自己的分解。希望这能把事情弄清楚!在

相关问题 更多 >