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?
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 :
If you are interested, it is available here.