如何求解2变量线性联立方程?爪哇 [英] How to solve a 2 variable linear simultaneous equation? Java

查看:55
本文介绍了如何求解2变量线性联立方程?爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说你有

3x + 2y = 11 
2x - 3y = 16  

您将如何在Java中计算 x和y ?

How would you work out x and y in Java?

做完一些代数运算后,我发现 x = de-bf/ad-bc y = af-ce/ad-bc

After doing some algebra I figured out that x = de-bf / ad-bc and y = af-ce / ad-bc

这些显示字母是什么 a + b = e c + d = f

These show what the letters are a + b = e and c + d = f

每当我编写代码时,它总是给我错误的答案,我不确定这是否是由于使用int而不是double或其他原因造成的.也可以解析方程式中的字母,例如

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

这是没有解析的代码

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);
}

推荐答案

问题是您将行列式两次除法!

The problem is that you divide your determinant twice!

您的公式是

x = de-bf / ad-bc
y = af-ce / ad-bc

det = ad-bc

如此:

x = de-bf / det 
y = af-ce / det 

但是你计算:

double det = 1/ ((a) * (d) - (b) * (c));

因此您程序中的 det 不是来自公式的 det ,而是 1/det

so in your program det is not det from the formula, but 1/det!

所以您可以纠正:

double det =((a)*(d)-(b)*(c));

double det = ((a) * (d) - (b) * (c));

double x =((d)*(e)-(b)*(f))* det;double y =((a)*(f)-(c)*(e))* det;

double x = ((d) * (e) - (b) * (f)) * det; double y = ((a) * (f) - (c) * (e)) * det;

我喜欢第一个:

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变量线性联立方程?爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆