Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for evaluating math expressions in Java

Tags:

java

math

formula

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?

like image 837
Ethan Leroy Avatar asked Aug 31 '11 14:08

Ethan Leroy


People also ask

How do you evaluate mathematical expressions?

To evaluate an algebraic expression, you have to substitute a number for each variable and perform the arithmetic operations. In the example above, the variable x is equal to 6 since 6 + 6 = 12. If we know the value of our variables, we can replace the variables with their values and then evaluate the expression.

What is evaluation of expression?

To evaluate an algebraic expression means to find the value of the expression when the variable is replaced by a given number. To evaluate an expression, we substitute the given number for the variable in the expression and then simplify the expression using the order of operations.


1 Answers

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.

like image 146
fasseg Avatar answered Oct 27 '22 01:10

fasseg