稀疏矩阵的行列式,由未成年人扩展,Python3

时间:2018-06-29 20:07:57

标签: python python-3.x determinants

我希望在下面提高行列式函数的速度和内存使用率。任何见解将不胜感激。

注释

  1. 我知道计算行列式的更快方法(LU分解等),但是我对那些用于特定任务的方法不感兴趣。

  2. 主要目的是查看未成年人对大型稀疏矩阵的扩展速度和存储效率如何

  3. 我对大型(> 1000x1000)矩阵感兴趣,该矩阵在每列中都有大约5个条目

    import numpy as np
    import scipy as sp
    
    N = 20
    a = sp.sparse.diags([-1, 2, -1], [-1, 0, 1], shape=(N, N))
    b = a.tocoo()
    c = np.zeros((b.count_nonzero(),3))
    c[:,0] = b.row
    c[:,1] = b.col
    c[:,2] = b.data
    
    def determinantS(C,M):
        d=0
        # check for 1x1 matrix
        if (C.shape[0] == 1): 
            if C[0,0] == 0 and C[0,1] == 0: 
                return C[0,2]
            else:
                return 0
        setrange = set(range(M))
        # check for a zero row
        if set(C[:,0]) != setrange:
            d = 0
        # check for a zero column
        elif set(C[:,1]) != setrange:
            d = 0
        # expand by minors along first row
        else:
            row = np.where(C[:,0] == 0)[0] # identify first row
            B = C[ C[:,0]>0 , : ] # remove first row
            B[:,0] += -1 # reindex
            for ii in row:
                Bi = B[ B[:,1]!=C[ii,1] , : ] # remove column ii (create minor)
    
                #check for empty matrix 
                if len(Bi):
                    Bi[ Bi[:,1]>C[ii,1] , 1] += -1 # reindex
                    d += (-1)**C[ii,1] * C[ii,2] * determinantS(Bi,M-1) 
        return(d)  
    

    det1 =行列式S(c,N)

0 个答案:

没有答案