问题
For the purposes of what I want to do I need to take a user input as a string and convert it into an unevaluated function. For example, if the user input was "x^2*sin(x)" I would need a function that took a double input x and returned
Math.Pow(x, 2)*Math.Sin(x)
I need the function, I can't pass in a value for x and I will be calling the function many times (hundreds possibly) so I can't parse the string each time I am making a calculation.
How would I implement this? I take it from the question Convert a string into mathematical equation? that there is not a standard way to do this. But I am a little lost as to how to "save" a mathematical formula, is there a way to create a delegate with the math expression?
At the very least, I need it to recognize basic algebra equations, powers, exponentials, and trig functions. Also, although I used the example of a function of a single variable x, I want to be able to parse a function of multiple variables.
回答1:
Essentially, you need to implement your own syntax parser and convert input string into an Expression Tree.
回答2:
I ended up 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.
来源:https://stackoverflow.com/questions/32333134/turn-user-input-string-into-mathematical-function