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?
Nice math parser containing broad math collection - mXparser - please see the examples:
Example 1:
Result:
Example 2:
Result:
For better understanding please follow mXparser tutorial and mXparser math collection.
Best regards
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:When using a newer API version like
0.4.8
:There's also a facility to use custom functions in exp4j.
It depends how complex are the expressions you want to eval but for simple ones, java has a javascript engine that works pretty well:
Adding another option to the list, I wrote Jep Java which gained a lot of popularity as an open source project on sourceforge.
It supports all the basic common tasks of expression parsing. But it also adds a lot of extendibility if you want to customize it. A lot of users have praised the library for being especially well written and easy to use. See the sourceforge reviews!
Here is a simple example with a single variable:
This will print "x + 1 = 11". You can change the value of variables and quickly evaluate the expression again.
I later also made the library available with a commercial license on the Singular Systems website.
To extend the list, I just have finished one, too:
https://github.com/uklimaschewski/EvalEx
EvalEx is a handy expression evaluator for Java, that allows to evaluate simple mathematical and boolean expressions.
Key Features:
Examples:
I have a small-footprint yet very capable math evaluator which is completely unencumbered.
Primary Features
+
-
*
×
/
÷
%
^
).0x
.Here's a simple example which calculates the middle column of the subsection of a text display (biased left).