如何求解大矩阵的行列式

14

我找到了一些用于计算矩阵行列式的 C++ 代码,适用于 4x4 到 8x8 的矩阵。虽然它可以正常工作,但是我的项目需要一个 18x18 或更大的矩阵,而这段代码运行速度太慢了。该代码使用递归,但是递归是否是处理 18x18 矩阵的正确概念呢?还有其他方法来计算行列式吗?

5个回答

27

我假设您正在使用扩展 Laplace 公式naive 方法。如果您想要提高速度,可以使用 LU 分解(将矩阵 M 分解为两个下三角和上三角矩阵)来分解您的矩阵,您可以通过修改的高斯-约旦消元在 2*n^3/3 FLOPS 中实现,然后按如下方式计算行列式:

det(M) = det(L) * det(U),对于三角形矩阵,它只是它们对角线条目的乘积。

这个过程仍然比 O(n!) 更快。

编辑: 您还可以使用广泛实现的 Crout 方法


如果矩阵是对称正定的,那么Cholesky分解是最快、数值最佳的方法。 - Paul
@Paul:确实如此,但我不确定如何验证矩阵是正定的,所以我跳过了。 - Michael Foukarakis
计算一个三角矩阵的行列式是很简单的:只需将对角线上的元素相乘即可,因为非对角线上元素的余子式都为零。使用LU分解可以进一步简化计算,因为L是一个单位下三角矩阵,即其对角线元素均为1,在大多数实现中都是如此。因此,你通常只需要计算U的行列式即可。 - rcollyer
@rcollyer:你说的有一半对 - L(或U)并不总是单位三角矩阵,即使它可以是,如果你在做作业,找到它也不是很直观。;-) - Michael Foukarakis
就我个人而言,我发现Doolittle算法比Crout的更易于实现和理解。我还能稍微调整一下它来支持多线程。 - Phil

9

在这个领域工作的人中,很少有人认为18x18是一个大矩阵,而且你选择的任何技术都应该足够快,在任何现代计算机上。我们中的许多人不会使用递归算法来处理矩阵问题,更有可能使用迭代算法——但这可能反映出许多处理矩阵问题的人是科学家和工程师,而不是计算机科学家。

我建议您查看C++数值计算方法。它不一定是您能找到的最好的代码,但它是一个学习和借鉴的文本。对于更好的代码,BOOST有良好的声誉,还有BLAS和像英特尔数学核心库或AMD Core数学库之类的东西。我认为所有这些都有求解行列式的实现,可以非常快速地处理18x18矩阵。


3
由于我无法进行评论,因此我想补充一下:Cholesky分解(或其变体LDLT,其中L是一个单位下三角矩阵,D是一个对角矩阵)可用于验证对称矩阵是否为正/负定:如果它是正定的,则D的元素都是正的,并且Cholesky分解将成功完成而不需要对负数取平方根。如果矩阵是负定的,则D的元素全为负,矩阵本身将没有Cholesky分解,但它的相反数会有。

“计算三角矩阵的行列式很简单:乘以对角线元素,因为非对角线项的余子式为0。使用LU分解进一步简化了这个过程,因为L是一个单位下三角矩阵,即其对角线元素都为1,在大多数实现中。因此,您通常只需要计算U的行列式。”

  • 您在这里忘记考虑高斯消元的所有实际实现都利用(部分)枢轴选取来提高数值稳定性;因此,您的描述是不完整的;在分解阶段期间计算行交换次数,并在将U的对角线元素全部相乘后,如果交换次数为奇数,则应该对此乘积取反。

至于代码,NR不是免费的;我建议您查看LAPACK/CLAPACK/LAPACK++ @ http://www.netlib.org/。关于参考资料,我无法比“矩阵计算”一书更好的了,该书由Golub和Van Loan编写。


1

函数det_recursive适用于任何大小的方阵。但是,由于它使用Laplace公式的递归朴素方法,因此对于大型矩阵来说速度非常慢。

另一种技术是使用高斯消元技术将矩阵转换为上三角形式。然后,矩阵的行列式只是原始矩阵的三角形变换形式的对角线元素的乘积。

基本上,numpy是最快的,但在内部它使用类似于高斯消元的线性矩阵转换方法。但是,我不确定它到底是什么!

In[1]
import numpy as np

In[2]
mat = np.random.rand(9,9)
print("numpy asnwer = ", np.linalg.det(mat))

Out[2] 
numpy asnwer =  0.016770106020608373

In[3]
def det_recursive(A):
    if A.shape[0] != A.shape[1]:
        raise ValueError('matrix {} is not Square'.format(A))

    sol = 0
    if A.shape != (1,1):
        for i in range(A.shape[0]):
            sol = sol +  (-1)**i * A[i, 0] * det_recursive(np.delete(np.delete(A, 0, axis= 1), i, axis= 0))
        return sol
    else:
        return A[0,0]
​

In[4]
print("recursive asnwer = ", det_recursive(mat))

Out[4]
recursive asnwer =  0.016770106020608397

In[5]
def det_gauss_elimination(a,tol=1.0e-9):
    """
    calculate determinant using gauss-elimination method
    """
    a = np.copy(a)

    assert(a.shape[0] == a.shape[1])
    n = a.shape[0]

    # Set up scale factors
    s = np.zeros(n)

    mult = 0
    for i in range(n):
        s[i] = max(np.abs(a[i,:])) # find the max of each row
    for k in range(0, n-1): #pivot row
        # Row interchange, if needed
        p = np.argmax(np.abs(a[k:n,k])/s[k:n]) + k 
        if abs(a[p,k]) < tol: 
            print("Matrix is singular")
            return 0
        if p != k: 
            a[[k,p],:] = a[[p, k],:] 
            s[k],s[p] = s[p],s[k]
            mult = mult + 1
​
        # convert a to upper triangular matrix
        for i in range(k+1,n):
            if a[i,k] != 0.0: # skip if a(i,k) is already zero
                lam = a [i,k]/a[k,k] 
                a[i,k:n] = a[i,k:n] - lam*a[k,k:n]
​
    deter = np.prod(np.diag(a))* (-1)**mult   
    return deter

In[6] 
print("gauss elimination asnwer = ", det_gauss_elimination(mat))

Out[6] 
gauss elimination asnwer =  0.016770106020608383

In[7] 
print("numpy time")
%timeit -n3 -r3 np.linalg.det(mat)
print("\nrecursion time")
%timeit -n3 -r3 det_recursive(mat)
print("\ngauss_elimination time")
%timeit -n3 -r3 det_gauss_elimination(mat)

Out[7]
numpy time
40.8 µs ± 17.2 µs per loop (mean ± std. dev. of 3 runs, 3 loops each)

recursion time
10.1 s ± 128 ms per loop (mean ± std. dev. of 3 runs, 3 loops each)

gauss_elimination time
472 µs ± 106 µs per loop (mean ± std. dev. of 3 runs, 3 loops each)

0

我认为这可能有效。我在学习数值分析课程时编写了它。这不仅是行列式,还包括与矩阵相关的其他函数。

首先,将此代码复制并保存为Matrix.h

//Title: Matrix Header File
//Writer: Say OL
//This is a beginner code not an expert one
//No responsibilty for any errors
//Use for your own risk

using namespace std;
int row,col,Row,Col;
double Coefficient;

//Input Matrix
void Input(double Matrix[9][9],int Row,int Col)
{
    for(row=1;row<=Row;row++)
        for(col=1;col<=Col;col++)
        {
            cout<<"e["<<row<<"]["<<col<<"]=";
            cin>>Matrix[row][col];
        }
}

//Output Matrix
void Output(double Matrix[9][9],int Row,int Col)
{
    for(row=1;row<=Row;row++)
    {
        for(col=1;col<=Col;col++)
            cout<<Matrix[row][col]<<"\t";
        cout<<endl;
    }
}

//Copy Pointer to Matrix
void CopyPointer(double (*Pointer)[9],double Matrix[9][9],int Row,int Col)
{
    for(row=1;row<=Row;row++)
        for(col=1;col<=Col;col++)
            Matrix[row][col]=Pointer[row][col];
}

//Copy Matrix to Matrix
void CopyMatrix(double MatrixInput[9][9],double MatrixTarget[9][9],int Row,int Col)
{
    for(row=1;row<=Row;row++)
        for(col=1;col<=Col;col++)
            MatrixTarget[row][col]=MatrixInput[row][col];
}

//Transpose of Matrix
double MatrixTran[9][9];
double (*(Transpose)(double MatrixInput[9][9],int Row,int Col))[9]
{
    for(row=1;row<=Row;row++)
        for(col=1;col<=Col;col++)
            MatrixTran[col][row]=MatrixInput[row][col];
    return MatrixTran;
}

//Matrix Addition
double MatrixAdd[9][9];
double (*(Addition)(double MatrixA[9][9],double MatrixB[9][9],int Row,int Col))[9]
{
    for(row=1;row<=Row;row++)
        for(col=1;col<=Col;col++)
            MatrixAdd[row][col]=MatrixA[row][col]+MatrixB[row][col];
    return MatrixAdd;
}

//Matrix Subtraction
double MatrixSub[9][9];
double (*(Subtraction)(double MatrixA[9][9],double MatrixB[9][9],int Row,int Col))[9]
{
    for(row=1;row<=Row;row++)
        for(col=1;col<=Col;col++)
            MatrixSub[row][col]=MatrixA[row][col]-MatrixB[row][col];
    return MatrixSub;
}

//Matrix Multiplication
int mRow,nCol,pCol,kcol;
double MatrixMult[9][9];
double (*(Multiplication)(double MatrixA[9][9],double MatrixB[9][9],int mRow,int nCol,int pCol))[9]
{
    for(row=1;row<=mRow;row++)
        for(col=1;col<=pCol;col++)
        {
            MatrixMult[row][col]=0.0;
            for(kcol=1;kcol<=nCol;kcol++)
                MatrixMult[row][col]+=MatrixA[row][kcol]*MatrixB[kcol][col];
        }
    return MatrixMult;
}

//Interchange Two Rows
double RowTemp[9][9];
double MatrixInter[9][9];
double (*(InterchangeRow)(double MatrixInput[9][9],int Row,int Col,int iRow,int jRow))[9]
{
    CopyMatrix(MatrixInput,MatrixInter,Row,Col);
    for(col=1;col<=Col;col++)
    {
        RowTemp[iRow][col]=MatrixInter[iRow][col];
        MatrixInter[iRow][col]=MatrixInter[jRow][col];
        MatrixInter[jRow][col]=RowTemp[iRow][col];
    }
    return MatrixInter;
}

//Pivote Downward
double MatrixDown[9][9];
double (*(PivoteDown)(double MatrixInput[9][9],int Row,int Col,int tRow,int tCol))[9]
{
    CopyMatrix(MatrixInput,MatrixDown,Row,Col);
    Coefficient=MatrixDown[tRow][tCol];
    if(Coefficient!=1.0)
        for(col=1;col<=Col;col++)
            MatrixDown[tRow][col]/=Coefficient;
    if(tRow<Row)
        for(row=tRow+1;row<=Row;row++)
        {
            Coefficient=MatrixDown[row][tCol];
            for(col=1;col<=Col;col++)
                MatrixDown[row][col]-=Coefficient*MatrixDown[tRow][col];
        }
return MatrixDown;
}

//Pivote Upward
double MatrixUp[9][9];
double (*(PivoteUp)(double MatrixInput[9][9],int Row,int Col,int tRow,int tCol))[9]
{
    CopyMatrix(MatrixInput,MatrixUp,Row,Col);
    Coefficient=MatrixUp[tRow][tCol];
    if(Coefficient!=1.0)
        for(col=1;col<=Col;col++)
            MatrixUp[tRow][col]/=Coefficient;
    if(tRow>1)
        for(row=tRow-1;row>=1;row--)
        {
            Coefficient=MatrixUp[row][tCol];
            for(col=1;col<=Col;col++)
                MatrixUp[row][col]-=Coefficient*MatrixUp[tRow][col];
        }
    return MatrixUp;
}

//Pivote in Determinant
double MatrixPiv[9][9];
double (*(Pivote)(double MatrixInput[9][9],int Dim,int pTarget))[9]
{
    CopyMatrix(MatrixInput,MatrixPiv,Dim,Dim);
    for(row=pTarget+1;row<=Dim;row++)
    {
        Coefficient=MatrixPiv[row][pTarget]/MatrixPiv[pTarget][pTarget];
        for(col=1;col<=Dim;col++)
        {
            MatrixPiv[row][col]-=Coefficient*MatrixPiv[pTarget][col];
        }
    }
    return MatrixPiv;
}

//Determinant of Square Matrix
int dCounter,dRow;
double Det;
double MatrixDet[9][9];
double Determinant(double MatrixInput[9][9],int Dim)
{
    CopyMatrix(MatrixInput,MatrixDet,Dim,Dim);
    Det=1.0;
    if(Dim>1)
    {
        for(dRow=1;dRow<Dim;dRow++)
        {
            dCounter=dRow;
            while((MatrixDet[dRow][dRow]==0.0)&(dCounter<=Dim))
            {
                dCounter++;
                Det*=-1.0;
                CopyPointer(InterchangeRow(MatrixDet,Dim,Dim,dRow,dCounter),MatrixDet,Dim,Dim);
            }
            if(MatrixDet[dRow][dRow]==0)
            {
                Det=0.0;
                break;
            }
            else
            {
                Det*=MatrixDet[dRow][dRow];
                CopyPointer(Pivote(MatrixDet,Dim,dRow),MatrixDet,Dim,Dim);
            }
        }
        Det*=MatrixDet[Dim][Dim];
    }
    else Det=MatrixDet[1][1];
    return Det;
}

//Matrix Identity
double MatrixIdent[9][9];
double (*(Identity)(int Dim))[9]
{
    for(row=1;row<=Dim;row++)
        for(col=1;col<=Dim;col++)
            if(row==col)
                MatrixIdent[row][col]=1.0;
            else
                MatrixIdent[row][col]=0.0;
    return MatrixIdent;
}
//Join Matrix to be Augmented Matrix
double MatrixJoin[9][9];
double (*(JoinMatrix)(double MatrixA[9][9],double MatrixB[9][9],int Row,int ColA,int ColB))[9]
{
    Col=ColA+ColB;
    for(row=1;row<=Row;row++)
        for(col=1;col<=Col;col++)
            if(col<=ColA)
                MatrixJoin[row][col]=MatrixA[row][col];
            else
                MatrixJoin[row][col]=MatrixB[row][col-ColA];
    return MatrixJoin;
}

//Inverse of Matrix
double (*Pointer)[9];
double IdentMatrix[9][9];
int Counter;
double MatrixAug[9][9];
double MatrixInv[9][9];
double (*(Inverse)(double MatrixInput[9][9],int Dim))[9]
{
    Row=Dim;
    Col=Dim+Dim;
    Pointer=Identity(Dim);
    CopyPointer(Pointer,IdentMatrix,Dim,Dim);
    Pointer=JoinMatrix(MatrixInput,IdentMatrix,Dim,Dim,Dim);
    CopyPointer(Pointer,MatrixAug,Row,Col);
    for(Counter=1;Counter<=Dim;Counter++)   
    {
        Pointer=PivoteDown(MatrixAug,Row,Col,Counter,Counter);
        CopyPointer(Pointer,MatrixAug,Row,Col);
    }
    for(Counter=Dim;Counter>1;Counter--)
    {
        Pointer=PivoteUp(MatrixAug,Row,Col,Counter,Counter);
        CopyPointer(Pointer,MatrixAug,Row,Col);
    }
    for(row=1;row<=Dim;row++)
        for(col=1;col<=Dim;col++)
            MatrixInv[row][col]=MatrixAug[row][col+Dim];
    return MatrixInv;
}

//Gauss-Jordan Elemination
double MatrixGJ[9][9];
double VectorGJ[9][9];
double (*(GaussJordan)(double MatrixInput[9][9],double VectorInput[9][9],int Dim))[9]
{
    Row=Dim;
    Col=Dim+1;
    Pointer=JoinMatrix(MatrixInput,VectorInput,Dim,Dim,1);
    CopyPointer(Pointer,MatrixGJ,Row,Col);
    for(Counter=1;Counter<=Dim;Counter++)   
    {
        Pointer=PivoteDown(MatrixGJ,Row,Col,Counter,Counter);
        CopyPointer(Pointer,MatrixGJ,Row,Col);
    }
    for(Counter=Dim;Counter>1;Counter--)
    {
        Pointer=PivoteUp(MatrixGJ,Row,Col,Counter,Counter);
        CopyPointer(Pointer,MatrixGJ,Row,Col);
    }
    for(row=1;row<=Dim;row++)
        for(col=1;col<=1;col++)
            VectorGJ[row][col]=MatrixGJ[row][col+Dim];
    return VectorGJ;
}

//Generalized Gauss-Jordan Elemination
double MatrixGGJ[9][9];
double VectorGGJ[9][9];
double (*(GeneralizedGaussJordan)(double MatrixInput[9][9],double VectorInput[9][9],int Dim,int vCol))[9]
{
    Row=Dim;
    Col=Dim+vCol;
    Pointer=JoinMatrix(MatrixInput,VectorInput,Dim,Dim,vCol);
    CopyPointer(Pointer,MatrixGGJ,Row,Col);
    for(Counter=1;Counter<=Dim;Counter++)   
    {
        Pointer=PivoteDown(MatrixGGJ,Row,Col,Counter,Counter);
        CopyPointer(Pointer,MatrixGGJ,Row,Col);
    }
    for(Counter=Dim;Counter>1;Counter--)
    {
        Pointer=PivoteUp(MatrixGGJ,Row,Col,Counter,Counter);
        CopyPointer(Pointer,MatrixGGJ,Row,Col);
    }
    for(row=1;row<=Row;row++)
        for(col=1;col<=vCol;col++)
            VectorGGJ[row][col]=MatrixGGJ[row][col+Dim];
    return VectorGGJ;
}

//Matrix Sparse, Three Diagonal Non-Zero Elements
double MatrixSpa[9][9];
double (*(Sparse)(int Dimension,double FirstElement,double SecondElement,double ThirdElement))[9]
{
    MatrixSpa[1][1]=SecondElement;
    MatrixSpa[1][2]=ThirdElement;
    MatrixSpa[Dimension][Dimension-1]=FirstElement;
    MatrixSpa[Dimension][Dimension]=SecondElement;
    for(int Counter=2;Counter<Dimension;Counter++)
    {
        MatrixSpa[Counter][Counter-1]=FirstElement;
        MatrixSpa[Counter][Counter]=SecondElement;
        MatrixSpa[Counter][Counter+1]=ThirdElement;
    }
    return MatrixSpa;
}
在我的方法中,我使用初等行变换将矩阵转换为上三角矩阵。行列式是对角线元素的乘积。 以下是示例代码:
#include<iostream>
#include<conio.h>
#include"Matrix.h"

int Dim;
double Matrix[9][9];

int main()
{
    cout<<"Enter matrix dimension: ";
    cin>>Dim;
    cout<<"Enter matrix elements:"<<endl;
    Input(Matrix,Dim,Dim);
    cout<<"Your matrix:"<<endl;
    Output(Matrix,Dim,Dim);
    cout<<"The determinant: "<<Determinant(Matrix,Dim)<<endl;
    getch();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,