Home > Enterprise >  Trying to find the inverse of the matrix in C, but the program is not calculating correctly
Trying to find the inverse of the matrix in C, but the program is not calculating correctly

Time:07-23

There was a question that I needed to find the inverse of the matrix (actually it's about cryptography, but never mind) and to be honest the code works. Nevertheless, if you insert certain numbers into the matrix, the program just fail in to calculate it. Let me show you the code:

#include <stdio.h>
#include <stdlib.h>

int main(){

int i, Mtx_P[4], temp;
float D, Mtx_I[4];

printf("\nInsert the values in a matrix 2x2: ");    // Insert the values

for(i=0;i<4;i  )
{
    scanf("%d", &Mtx_P[i]);
}


printf(" \n");

for(i=0;i<4;i  )    // Print the values
{
    printf("%d\t", Mtx_P[i]);

    if(i == 1)
    {
        printf("\n\n");
    }
}

D = (Mtx_P[0] * Mtx_P[3]) - (Mtx_P[1] * Mtx_P[2]);  // Find and print the determinant

printf("\n\n-------------------------\n\nDeterminant = %f\n", D);

float  Mtx_Pf[4];
//double Mtx_Pf[4];  I've tried with double to see if worked

for(i=0;i<4;i  )    // Find the inverse...
{
    Mtx_Pf[i] = Mtx_P[i];       
}

Mtx_I[0] = Mtx_Pf[0]/D;     // ...divind the values by the determinat
Mtx_I[1] = Mtx_Pf[1]/D;
Mtx_I[2] = Mtx_Pf[2]/D;
Mtx_I[3] = Mtx_Pf[3]/D;

temp = Mtx_I[0];    // swaping the places of the first number with the lastest one
Mtx_I[0] = Mtx_I[3];
Mtx_I[3] = temp;

Mtx_I[1]*=-1;   // the secondary diagonal get negative
Mtx_I[2]*=-1;

printf("\n-------------------------\n\nThe invertible Matrix:\n\n ");

for(i=0;i<4;i  )    // Print the inverse
{
    printf("%f\t", Mtx_I[i]);

    if(i == 1)
    {
        printf("\n\n");
    }
}

double test = 1/(-26);
printf("\n\n-------------------------\n(Test: %lf)\n\n", test); // Testing to see if it can't calculate

return 0;
}

My problem happens when I try to divide the element by the determinant using this matrix:

1       10

3       4

When is the time to calculate 1 by -26 (determinant) it prints 0,0000, but actually 1/(-26) is −0,038461538 (according to the calculator).

You probaly already realize that this trouble doesn't have any relation with matrixes, but somebody knows how to fix this error?

CodePudding user response:

The issue is that your temp variable (used for swapping) is an int and assigning a float to an int truncates the value. Define it as a float or double instead.

float D, Mtx_I[4], temp;

In addition, note that 1/(-26) is integer division, resulting in truncation. To perform floating-point division, one of the operands must be a floating-point value (e.g. 1./-26).

  • Related