行列式的行列式给了我一些错误的数字

时间:2019-06-05 01:51:36

标签: c

我编写了此程序,该程序从文件中读取值,其中前两个是矩阵的维,其余是值。然后,将值放入矩阵中并计算行列式。

matrix.c

void matrix(FILE *fp) {
    float fval[102];
    int n, i;

    //scan floats into fval
    if (fp != NULL) {
        fputs("0.000   1.800   3.240   4.374   5.249   5.905   6.377   7.696 ", fp);
        rewind(fp);

        n = 0;
        while (fscanf(fp, "%f", &fval[n++]) != EOF);


    }
    //The first two values in the file are the NXN dimensions, so
    //take every value after that into new array
    double matrix[n];
    //I find that I have to convert the array to doubles otherwise
    //the matrix will have a bunch of random numbers
    for(i = 2;i<n;i++){
    matrix[i-2]=fval[i];}

    Matrix* m1 = copy_matrix(matrix,(int)fval[1]); //copies array and makes 2d matrix 
    print_matrix(m1);
    determinant(m1->mat,(int)fval[1]);
}

Matrix* make_matrix(int N) {
    struct Matrix* matrix = malloc(sizeof(Matrix));
    matrix->dim = N;
    matrix->dim = N;
    double** mat = malloc(sizeof(double*) * N);
    for(int x = 0; x < N; x++){
        mat[x] = calloc(N, sizeof(double));
    }
    matrix->mat = mat;

    for(int x = 0; x < N; x++) {
        for(int y = 0; y < N; y++) {
            matrix->mat[x][y] = 4;
        }
    }

    return matrix;
}

Matrix* copy_matrix(double* new, int N) {
    struct Matrix *matrix = make_matrix(N);
    for(int x = 0; x < N; x++) {
        for(int y = 0; y < N; y++) {
            matrix->mat[x][y] = new[N*x+y];
        }
    }
    return matrix;
}
double determinant(double **matrix, int n)
{
    float ratio, det;
    int i, j, k;
    //print
    /* Conversion of matrix to upper triangular */
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            if(j>i){
                ratio = matrix[j][i]/matrix[i][i];
                for(k = 0; k < n; k++){
                    matrix[j][k] -= ratio * matrix[i][k];
                }
            }
        }
    }
    det = 1; //storage for determinant
    for(i = 0; i < n; i++)
        det *= matrix[i][i];
    printf("The determinant is %.2f.\n", det);

}

我的问题是,它给了我几乎正确的答案,但是它的影响很小。例如,

-18.26 34.63 44.52 -9.84
49.84 -43.78 31.26 37.53
-34.91 20.56 5.89 45.52
-29.0 4.0 38.25 13.88

此4x4矩阵的行列式为6125131.30。我的程序给了我6125131.50。可能是什么问题?

0 个答案:

没有答案