将用户输入的字符串转换为数学函数 [英] Turn user input string into mathematical function

查看:130
本文介绍了将用户输入的字符串转换为数学函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于我想要做的目的,我需要将用户输入作为字符串并将其转换为未评估的函数.例如,如果用户输入为"x ^ 2 * sin(x)",则我需要一个接受双输入x并返回

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)

我需要该函数,我无法传递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?

至少,我需要它来识别基本的代数方程,幂,指数和三角函数.另外,尽管我以单个变量x的函数为例,但我希望能够解析多个变量的函数.

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.

推荐答案

我最终使用了 NCalc .我传入了用户的字符串表达式,用要评估的值替换了变量,然后使用Evaluate方法并解析为double.

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;        
    }

例如,给定输入t = .5和y = 1且表达式为"4 * y + Tan(2 * t)",我们将评估字符串"4 * 1 + Tan(2 * .5) 使用NCalc.

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.

这不是完美的,如果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.

这篇关于将用户输入的字符串转换为数学函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆