Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algebra equation parser for java

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

like image 610
Alfredo Osorio Avatar asked Jan 13 '11 15:01

Alfredo Osorio


3 Answers

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.

like image 148
Bart Kiers Avatar answered Nov 14 '22 09:11

Bart Kiers


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!

like image 18
fasseg Avatar answered Nov 14 '22 09:11

fasseg


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

like image 3
Leroy Kegan Avatar answered Nov 14 '22 10:11

Leroy Kegan