Method for evaluating math expressions in Java

Ethan Leroy picture Ethan Leroy · Aug 31, 2011 · Viewed 77.6k times · Source

In one of my projects I want to add a feature where the user can provide in a formula, for example

sin (x + pi)/2 + 1

which I use in my Java app

/**
 * The formula provided by the user
 */
private String formula; // = "sin (x + pi)/2 + 1"

/*
 * Evaluates the formula and computes the result by using the
 * given value for x
 */
public double calc(double x) {
    Formula f = new Formula(formula);
    f.setVar("x", x);
    return f.calc();
    // or something similar
}

How can I evaluate math expressions?

Answer

fasseg picture fasseg · Nov 15, 2011

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.