Reputation: 31
I'm a beginner. I want to convert a string into a mathematical equation in order to be the input of my graphic calculator for example:
cos(x+1)+ ln(x)
so we will convert it to
double x = -10;
for (int i=0; i<100; i++) {
double y=Math.cos(x+1)+Math.log(x)
x=x+0.5
}
so I want to know a method of converting y
Thank You
Upvotes: 2
Views: 3868
Reputation: 491
I did that exact thing using NCalc. I passed in the user's string expression, replaced the variables with the values I am evaluating at, then using the Evaluate method and parsing to a double.
private double Function(double t, double y)
{
NCalc.Expression expression = new NCalc.Expression(this.Expression);
expression.Parameters["t"] = t;
expression.Parameters["y"] = y;
double value;
double.TryParse(expression.Evaluate().ToString(), out value);
return value;
}
For example, given the inputs t = .5 and y = 1 and the expression "4*y + Tan(2*t)", we would evaluate the string "4*1 + Tan(2*.5)" using NCalc.
It is not perfect, NCalc throws an exception if it cannot parse the user's string or it the datatypes of functions are different. I am working on polishing it.
I also asked the same question here.
Upvotes: 1
Reputation: 426
There is no "out-of-the-box" solution in java for this.
However: Obligatory answer: google -> "convert string to mathematical expression java" first few answers are pretty good (like: What's a good library for parsing mathematical expressions in java? ) Obligatory answer 2: There are quite a few libraries on the net for converting strings into math expressions, naming them would be off-topic according to the rules, so I suggest "Obligatory answer" first few hits.
Also most likely you are better off by choosing a Format you will receive, and write your own parser for that format.
Upvotes: 2
Reputation: 133
This is not a simple thing to do in pure Java. There are a lot of other similar questions with good answers here. Most of the solutions have to do with evaluating the expression in an interpreter or parsing the expression (there are some libraries available for this), or even shelling out. I don't know what is available in Android specifically to do this but there are tons of good answers for this in SO. Here is a good one to start with: Evaluating a math expression given in string form
Upvotes: 1
Reputation: 39457
You need to have a small formal grammar describing the syntax of your expression, then you need to convert your input string expression to an AST representation.
http://en.wikipedia.org/wiki/Abstract_syntax_tree
Finally you need to have a procedure to evaluate the AST for certain values of the parameters.
Upvotes: 1
Reputation: 772
You need to write a parser first, building a tree of your input expression. You can then use that to generate your code.
But, "I'm a beginner" doesn't go well with writing parsers :)
Upvotes: 1