Solving two algebraic equations in java

风格不统一 提交于 2019-12-11 19:17:46

问题


I have two equations that need to be evaluated in java

y=(x+1)*2-3
y=5

These equations are dynamic in nature

y= x*8x6-5*5
y= 3

y is known in these equations, I need to determine the value of x

What is the best and easy way to write a program in java?


回答1:


It seems that there are a couple of ways to go about this. My first thought (as always is overly complex and most likely not worth doing except for fun), is to use a create a grammar to parse out the order of operations, things that can evaluate to variables vs constants, etc. Then programatically solve the equations. This however is not something easily done. If this is for a compiler class, this might be worth looking at otherwise ignore it.

My second thought was to just use brute force. Though you will need to figure out what to do with negative values of x.

public int solve(int y){
    int x=0;
    while(y>(x+1)*2-3)
        x++;
}



回答2:


Some years later, hope this helps someone, to make this a lot simplier i will use the library exp4j (https://www.objecthunter.net/exp4j/) and the IDE netbeans 8.2 (https://netbeans.org/). Create a frame like this

Later on the button add the code:

try { net.objecthunter.exp4j.Expression e = new ExpressionBuilder(txtFunc.getText()) .variables("x") .build() .setVariable("x", Double.parseDouble(txtVar.getText())); double result = e.evaluate(); txtRes.setText("" + result); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Revisa la función o la variable, Posibles errores de operación: División entre 0"); }

Note: this is intended to evaluate "x" So doing specifically that way is going to be little bit complicated, so we are going to do some math, if 5 is the value of the function evaluated then we isolate the value of "x". x=(y+1)/2 then re-evaluate, x=(5+1)/2=3, x=3 and with the code verify that this is actually the answer.
Comprobation

Same thing goes with the other function. (sorry for my technical english)




回答3:


If by saying the equations are "dynamic" we are to infer that you are trying to construct a program to solve for x in an arbitrary algebraic equation (or set of equations), that's well beyond the scope of this forum. There are entire software packages designed to do things like that.



来源:https://stackoverflow.com/questions/15227122/solving-two-algebraic-equations-in-java

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