Method for evaluating math expressions in Java

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 about 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();

When using a newer API version like 0.4.8:

Expression calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
    .variable("x", x)
    .variable("y", y)
    .build();
double result1 = calc.evaluate();

There’s also a facility to use custom functions in exp4j.

Leave a Comment