help with simple matrix program

Sep 22, 2014 at 11:41pm
my professor wants me to create a program where it calculates the inverse of 2 matrices. he already made a program to show us what it looks like but i have to make the source file.
here is what he wants it to look like:
The inverse of:
(-2 -5)
(1 3)
is:
(-3 -5)
(1 2)

The inverse of:
(1 2)
(3 4)
is:
(-4 2)
(3 -1)
Press any key to continue . . .

and here is what i get when i run my program using bloodshell devc++:
The inverse of:
(-2 -5)
(1 3)
is:
(-3 -5)
(1 2)

The inverse of:
(1 2)
(3 4)
is:
(-2 1)
(1 0)
Press any key to continue . . .

i get a different inverse for the second matrix
does anyone know how to fix it and explain it, here is my source file:
#include<iostream>
#include<cstdlib>
using namespace std;

int main()
{
int a=-2, b=-5, c=1, d=3, f=a*d-b*c;
cout <<"The inverse of:" <<"\n"
<<"(-2 -5)" <<"\n"
<<"(1 3)" <<"\n"
<<"is:" <<"\n"
<<"(" <<d/f <<" " <<-b/f <<")" <<"\n"
<<"(" <<-c/f <<" " <<a/f <<")" <<"\n" <<"\n";

a=1, b=2, c=3, d=4, f=a*d-b*c;
cout <<"The inverse of:" <<"\n"
<<"(1 2)" <<"\n"
<<"(3 4)" <<"\n"
<<"is:" <<"\n"
<<"(" <<d/f <<" " <<-b/f <<")" <<"\n"
<<"(" <<-c/f <<" " <<a/f <<")" <<"\n";
system("pause");
return 0;
}

when i put the second matrix into a wolfram calculator it gives me this as the inverse:
0.5 (-4 2)
(3 -1)

what happened to the .5 in my professors program, and i think my program just distributed the .5 into the parenthesis?

thanks!!!!
Sep 23, 2014 at 3:30am
closed account (48T7M4Gy)
All your inputs are declared as integers. That's OK, more or less, if you add, multiply and subtract. But the moment you do a division then you will get truncation errors which means that decimals are cut off. Try declaring your variables as floats instead of ints.
Sep 23, 2014 at 3:33am
I don't know what the 0.5 is, but the problem with the calculation is that you're using int.
Integer division results in an integer and discards any rest. 3/2 equals 1 rest 1, but the rest is discarded.

For the second matrix, the determinant is -2
d/f == -4/2 == -2 rest 0
-b/f == 2/2 == 1 rest 0
-c/f == 3/2 == 1 rest 1
a/f == -1/2 == 0 rest 1


The first matrix turns out to be correct only because the determinant is 1.
Last edited on Sep 26, 2014 at 10:32am
Topic archived. No new replies allowed.