1. 程式人生 > >求解一個矩陣的逆矩陣

求解一個矩陣的逆矩陣

c++

#include<bits/stdc++.h>
using namespace std;
const int N=20;
const double E=1e-10;
double calculate_A(double src[N][N], int n )
{
    int i,j,k,x,y;
    double tmp[N][N], t;
    double result = 0.0;
    if(n == 1) return src[0][0];
    for( i = 0; i < n; ++i )
    {
        for( j = 0; j < n - 1; ++j )
        {
            for( k = 0; k < n - 1; ++k )
            {
                x = j + 1;
                y = k >= i ? k + 1 : k;

                tmp[j][k] = src[x][y];
            }
        }
        t = calculate_A( tmp, n - 1 );
        if( i % 2 == 0 ) result += src[0][i] * t;
        else result -= src[0][i] * t;
    }
    return result;
}

/**
 * 計算伴隨矩陣
 */
void calculate_A_adjoint( double src[N][N], double dst[N][N], int n )
{
    int i, j, k, t, x, y;
    double tmp[N][N];

    if( n == 1 )
    {
        dst[0][0] = 1;
        return;
    }

    for( i = 0; i < n; ++i )
    {
        for( j = 0; j < n; ++j )
        {
            for( k = 0; k < n - 1; ++k )
            {
                for( t = 0; t < n - 1; ++t )
                {
                    x = k >= i ? k + 1 : k ;
                    y = t >= j ? t + 1 : t;

                    tmp[k][t] = src[x][y];
                }
            }

            dst[j][i]  =  calculate_A( tmp, n - 1 );

            if( ( i + j ) % 2 == 1 )
            {
                dst[j][i] = -1*dst[j][i];
            }
        }
    }
}
/**
 * 得到逆矩陣
 */
int calculate_A_inverse( double src[N][N], double dst[N][N], int n )
{
    double A = calculate_A( src, n );
    double tmp[N][N];
    int i, j;
    if ( fabs( A - 0 ) <= E )
    {
        printf("不可能有逆矩陣!\n");
        return 0;
    }
    calculate_A_adjoint( src, tmp, n );

    for( i = 0; i < n; ++i )
    for( j = 0; j < n; ++j )
        dst[i][j] = (double)( tmp[i][j] / A );
    return 1;
}
int main()
{
    int n;
    double f[N][N],ans[N][N];
    cin>>n;
    for(int i=0;i<n;i++)
    for(int j=0;j<n;j++) cin>>f[i][j];
    calculate_A_inverse(f,ans,n);
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)printf("%lf ",ans[i][j]);
        cout<<endl;
    }
    return 0;
}
/*
輸入
3
3 2 0
2 1 2
2 1 1

輸出
-1 -2 4
2 3 -6
0 1 -1

*/

excel

http://blog.csdn.net/baimafujinji/article/details/49721523