任意输入数学表达式,绘制数学函数图形

来源:互联网 发布:人工智能项目 创始人 编辑:程序博客网 时间:2024/05/11 01:59

无意间闲逛时,在网上找到了一个.NET的坐标系统图形库:https://github.com/oxyplot/oxyplot/tree/master

很强大,WPF/Winform ,IOS, 安卓全支持,里面有一个例子是可以显示任意的数学函数图形,其代码类似:

var model = new PlotModel { Title = "ContextMenu" };

model.Series.Add(new FunctionSeries(Math.Sin, 0, 10, 200));

this.Model = model;

通过代码可以切换任意数学函数进行绘制,如是想到了高中时各种数学函数的绘制,可不可通过文本框输入数学表达式

然后进行任意绘制呢?然后在网上到处搜索有关“把字符串转换成数学表达式”的方案,结果搜索到了一篇神级的文章:

将字符串转换成Lambda 表达式

http://www.cnblogs.com/lenic/archive/2012/07/25/2607879.html,我想这就是我需要的,然后立马测试OK,大致使用的

代码如下:

           model.Series.Clear();  //调用就是刷新,不调用就是添加函数图形

           var funStr = "(x)=>System.Math.Atan(x)+x"; //必须使用完整的名称空间和C#形式的数学表达式
            try {
                System.Linq.Expressions.Expression<Func<double, double>> a = StringToLambda.LambdaParser.Parse<Func<double, double>>(funStr);
                model.Series.Add(new FunctionSeries(a.Compile(), 0, 10, 200));
            }
            catch(Exception err)
            {
                MessageBox.Show(err.ToString());
                model.Series.Add(new FunctionSeries(Math.Sin, 0, 10, 200));
            }


0 0
原创粉丝点击