问题
Say you have
3x + 2y = 11
2x - 3y = 16
How would you work out x and y
in Java?
After doing some algebra I figured out that x = de-bf / ad-bc
and y = af-ce / ad-bc
These show what the letters are
a + b = e
and c + d = f
Whenever I write the code it always gives me the wrong answer, I am not sure if that is due to using int instead of doubles or what. Would it also be possible to parse the letters from the equation e.g
input: 5x - 3y = 5
parased as: a = 5, b = -3 and e = 5
Here is the code without parsing
public static void solveSimultaneousEquations(double a, double b, double c, double d, double e, double f) {
double det = 1/ ((a) * (d) - (b) * (c));
double x = ((d) * (e) - (b) * (f)) / det;
double y = ((a) * (f) - (c) * (e)) / det;
System.out.print("x=" + x + " y=" + y);
}
回答1:
The problem is that you divide your determinant twice!
your formula is
x = de-bf / ad-bc
y = af-ce / ad-bc
det = ad-bc
so:
x = de-bf / det
y = af-ce / det
But you calculate:
double det = 1/ ((a) * (d) - (b) * (c));
so in your program det
is not det
from the formula, but 1/det
!
So either you correct:
double det = ((a) * (d) - (b) * (c));
or
double x = ((d) * (e) - (b) * (f)) * det; double y = ((a) * (f) - (c) * (e)) * det;
I prefer the first one:
public static void solveSimultaneousEquations(double a, double b, double c, double d, double e, double f) {
double det = ((a) * (d) - (b) * (c)); //instead of 1/
double x = ((d) * (e) - (b) * (f)) / det;
double y = ((a) * (f) - (c) * (e)) / det;
System.out.print("x=" + x + " y=" + y);
}
回答2:
Using Matrices is the easiest way to solve systems of equations
So, from your example:
3x + 7y = 41
5x - 3y = 25
You can actually create matrices
[[3 7]
[5 -3]]
and
[41 25]
Now, if you multiply both sides by the inverse of the left side matrix, you will have
[[1 0]
[0 1]]
on the left side, and the solution for both x and y on the right side
there used to be a matrix package that NASA had developed and made available where you could create matrices and do inverses. Look for that or something similar
来源:https://stackoverflow.com/questions/42279579/how-to-solve-a-2-variable-linear-simultaneous-equation-java