I’m trying to do a quick 2 vars equation solver using Cramer’s rule
but for some reason java keeps on rounding my answers so i don’t get the right answer.
the basic rule for getting single answer is
((a11*a22)-(a12*a21))!=0)
and the solution should be
double sol1 = (b1*a22-b2*a12) / (a11*a22-a12*a21);
double sol2 = (b2*a11-b1*a21) / (a11*a22-a12*a21);
but for some reason i get -4.0 and 4.0 instead of -4.0 and 4.5 for 1,2,3,4,5,6
that’s the problematic code if it helps:
if (((a11*a22)-(a12*a21))!=0) {
double sol1 = (b1*a22-b2*a12) / (a11*a22-a12*a21);
double sol2 = (b2*a11-b1*a21) / (a11*a22-a12*a21);
System.out.println("Single solution: ("+sol1+", "+sol2 +")");
}
Explicitly cast any of the variables as double before operation as:
or just multiply your one of the numbers by 1.0 to make them decimal as:
This is required because currently its performing operations on
intand resulting anintwhich is getting assigned todouble.Once you multiply your numerator or any of the participating variables by 1.0 or explicitly cast it to double, it becomes double and then remaining variables are auto promoted to double, which result into
doubleresult as desired.