Method for evaluating math expressions in Java

2019-01-01 07:07发布

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?

7条回答
看淡一切
2楼-- · 2019-01-01 07:57

I already have posted a similar answer here. I just wanted to say that I have been worked on a little library that supports math, boolean and string expression evaluation. Here is a small example :

String expression = "EXP(var)";
ExpressionEvaluator evaluator = new ExpressionEvaluator();
evaluator.putVariable(new Variable("var", VariableType.NUMBER, new BigDecimal(20)));

System.out.println("Value of exp(var) : " + evaluator.evaluate(expression).getValue());

If you are interested, it is available here.

查看更多
登录 后发表回答