I need a library to be able to parse an equation an give me the result giving the inputs.
For example something like this:
String equation = "x + y + z";
Map<String, Integer> vars = new HashMap<String, Integer>();
vars.add("x", 2);
vars.add("y", 1),
vars.add("z", 3);
EquationSolver solver = new EquationSolver(equation, vars);
int result = solver.getResult();
System.out.println("result: " + result);
And evaluates to: 6
Is there any kind of library for java that can do that for me?
Thanks
You could make use of Java 1.6's scripting capabilities:
import javax.script.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("x", 2);
vars.put("y", 1);
vars.put("z", 3);
System.out.println("result = "+engine.eval("x + y + z", new SimpleBindings(vars)));
}
}
which produces:
result = 6.0
For more complex expressions, JEP is a good choice.
There's also exp4j, an expression evaluator based on Dijkstra's Shunting Yard. It's freely available and redistributable under the Apache License 2.0, only 25kb in size and quite easy to use.
Calculable calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.withVariable("x", varX)
.withVariable("y", varY)
.build()
double result1=calc.calculate();
There's also a facility to use custom functions in exp4j.
exp4j - evaluate math expressions
have fun!
Try mXparser, below you will find usage example:
import org.mariuszgromada.math.mxparser.*;
...
...
String equation = "x + y + z";
Argument x = new Argument("x = 2");
Argument y = new Argument("y = 1");
Argument z = new Argument("z = 3");
Expression solver = new Expression(equation, x, y, z);
double result1 = solver.calculate();
System.out.println("result 1: " + result1);
x.setArgumentValue(3);
y.setArgumentValue(4);
z.setArgumentValue(5);
double result2 = solver.calculate();
System.out.println("result 2: " + result2);
Result:
result 1: 6.0
result 2: 12.0
Here the advantage of mXparser is that mXparser pre-compiles expression only once, and then, after arguments values changing, calculation is done very fast.
Follow the mXparser tutorial, mXparser math collection, mXparser API.
Additionally - this software is using mXparser as well - you can learn the syntax Scalar Calculator app.
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With