Turn user input string into mathematical function

后端 未结 2 1102
情话喂你
情话喂你 2021-01-06 17:41

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)\"

相关标签:
2条回答
  • 2021-01-06 18:17

    Essentially, you need to implement your own syntax parser and convert input string into an Expression Tree.

    0 讨论(0)
  • 2021-01-06 18:21

    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.

    0 讨论(0)
提交回复
热议问题