Python:计算任意n阶矩阵行列式

一些碎碎念

这是我第一次用CSDN,操作也在慢慢摸索。创这个博客的初衷是因为这学期的课程偏重于coding,machine learning 和 modeling。如果就这样学过去了过一段时间不温习很容易又忘掉,所以有时间就在博客里写写,记录一下各门课的收获,起到一个温故知新的作用。
第一篇文章,就谈点简单的东西,这是我CEE 490 Computer methods 第一次作业的一道coding,要求给出对任意n阶矩阵都成立的行列式计算代码。我当时在网上搜了搜,相关的代码很少,也没有多少参考价值,我最后就用Laplace formula写了这段代码,经验证也是成立的。

Codes

import numpy as np
np.set_printoptions(linewidth=400)

# generate a random 8*8 matrix
B = np.random.randn(8,8) 
print(B)

def det_calculation(arr):
    if arr.shape[0] == 1:
        return arr[0][0]
    S = 0
    for i in range(arr.shape[0]):
        arr1 = np.delete(arr,0,0) # delete first row
        arr1 = np.delete(arr1,i,1) # delete ith column
        S += (-1)**(1+i+1)*arr[0,i]*det_calculation(arr1) # Laplace formula
    return S

print('the calculated determinant of the random 8*8 matrix is',round(det_calculation(B),ndigits=3))
# Built in function of determinant is used to test the outcome
print('the actual determinant of the random 8*8 matrix is',round(np.linalg.det(B),ndigits=3))

随机生成的矩阵B结果如下:
Python:计算任意n阶矩阵行列式_第1张图片
用numpy内建function和我们定义的函数计算的行列式结果如下:

the calculated determinant of the random 88 matrix is -10.393
the actual determinant of the random 8
8 matrix is -10.393

你可能感兴趣的:(python,线性代数,矩阵)