Python实现部分主元法下LU分解
'''
《矩阵分析与应用》小作业1 实现部分主元法下的LU分解 by苗栋
程序大体介绍:
引入了numpy便于对数组的操作
①寻找出一列中绝对值最大的元素作为主元并进行数组的行交换,并将L主对角线元素置为1
②构造两个for循环,取出L和A对应的值并保存
L[j, i] = A[j, i] / A[i, i]
A[j, :] = A[j, :] - L[j, i] * A[i, :]
③最后打印结果
'''
import numpy
as np
def LU_with_partial_pivoting(A
):
A
= np
.array
(A
, dtype
=np
.float64
)
L
= np
.zeros_like
(A
)
m
= A
.shape
[0]
P
= np
.identity
(m
)
for i
in range(m
-1):
idx
= i
+ np
.argmax
(abs(A
[i
:, i
]))
if idx
!= i
& idx
!= m
-1:
A
[[i
, idx
], :] = A
[[idx
, i
], :]
L
[[i
, idx
], :] = L
[[idx
, i
], :]
P
[[i
, idx
], :] = P
[[idx
, i
], :]
L
[i
, i
] = 1
for j
in range(i
+1, m
):
L
[j
, i
] = A
[j
, i
] / A
[i
, i
]
A
[j
, :] = A
[j
, :] - L
[j
, i
] * A
[i
, :]
L
[i
+1, i
+1] = 1
U
= np
.array
(A
)
print('L矩阵为:\n', L
)
print('U矩阵为:\n', U
)
print('P矩阵为:\n', P
)
A
= np
.array
([[1, 2, -3, 4],
[4, 8, 12, -8],
[2, 3, 2, 1],
[-3, -1, 1, -4]])
LU_with_partial_pivoting
(A
)
转载请注明原文地址:https://blackberry.8miu.com/read-27286.html