在下面的代码中,我为通用矩阵A实现了LU分解。基于此实现,我编写了一个计算矩阵行列式的函数。我已经能够使用代码
为2x2矩阵确定它mat = [[1,0], [0,1]]
但是,现在我想通过生成100x100矩阵并计算该行列式来对其进行测试。那么如何将其放入代码中呢?我是否需要使用类似的
np.round(np.random.rand(100, 100)*10)
正在为此寻求帮助。这是我下面的代码!
def matrixMul(A, B):
TB = list(zip(*B))
return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]
def pivotize(m):
"""Creates the pivoting matrix for m."""
n = len(m)
ID = [[float(i == j) for i in range(n)] for j in range(n)]
r = 0
for j in range(n):
row = max(range(j, n), key=lambda i: abs(m[i][j]))
if j != row:
ID[j], ID[row] = ID[row], ID[j]
r += 1
return ID, r
def lu(A):
"""Decomposes a nxn matrix A by PA=LU and returns L, U and P."""
n = len(A)
L = [[0.0] * n for i in range(n)]
U = [[0.0] * n for i in range(n)]
P, r = pivotize(A)
A2 = matrixMul(P, A)
for j in range(n):
L[j][j] = 1.0
for i in range(j+1):
s1 = sum(U[k][j] * L[i][k] for k in range(i))
U[i][j] = A2[i][j] - s1
for i in range(j, n):
s2 = sum(U[k][j] * L[i][k] for k in range(j))
L[i][j] = (A2[i][j] - s2) / U[j][j]
return (L, U, P, r)
def trace(m):
n = len(m)
r = 1
for i in range(n):
if len(m[i]) <= i:
break
r *= m[i][i]
return r
def det(m):
l, u, p, r = lu(m)
return (-1)**r * trace(l) * trace(u)
mat = [[1,0], [0,1]]
print(det(mat))