How to solve a 2 variable linear simultaneous equation? Java

狂风中的少年 提交于 2021-01-28 08:16:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!