Turn user input string into mathematical function

只愿长相守 提交于 2019-12-01 00:06:14

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!