因此,我编写了一个python程序来计算nxn矩阵的行列式。它对3x3矩阵非常有效,但当我尝试输入4x4矩阵时,它给了我疯狂的值,甚至不接近正确的值,所以我想知道你是否可以告诉我我的代码哪里错了
import numpy as np
n = int(input('size:'))
mat = np.zeros((n,n))
d = 0
ep = 0
for i in range(n):
for j in range(n):
ep = int(input('mat[{},{}]='.format(i,j)))
mat[i,j] = ep
def submat(l,i,p):
m = []
sub = np.zeros((np.shape(l)[0]-1,np.shape(l)[0]-1))
for j in range(np.shape(l)[0]):
for k in range(np.shape(l)[0]):
if k == p or j == i:
continue
else:
m.append(l[j][k])
for j in range(np.shape(sub)[0]):
for k in range(np.shape(sub)[0]):
sub[j][k] = m[0]
m.remove(m[0])
return sub
def det(l,d):
if np.shape(l) == (2,2):
return l[0,0]*l[1,1] - l[1,0]*l[0,1]
elif np.shape(l) == (1,1):
return l[0,0]
else:
for i in range(np.shape(l)[0]):
print(d)
d += l[i][0]*((-1)**(i))*det(submat(l,i,0),d)
return d
p、 s:我检查了我编写的submat函数,问题肯定不在那里
1条答案
按热度按时间gg0vcinb1#
问题是你用什么来做
d
在你的det
功能。在删除它之后(我还自由地删除了2x2的特殊情况,因为拉普拉斯扩展也适用于此),我已经现在,我将您的结果与来自
numpy.linalg
```maximum = 0
argmax = None
for _ in range(104):
n = 4
mat = np.random.randint(100,10000,n2).reshape(n,n)
relative_error = np.abs((det(mat)-np.linalg.det(mat))/np.linalg.det(mat))
if relative_error > maximum:
maximum = relative_error
argmax = mat
maximum,np.linalg.det(argmax)-det(argmax),np.linalg.det(argmax),det(argmax)
(1.5070856755023637e-12, -0.24884033203125, 165113593789.75116, 165113593790.0)