3

I want to build in my application the possibility of drawing mathematical functions. In the plotting library that I'm using (OxyPlot) there is a great support for that. See this example:

y = ax³ + bx² + cx + d = 0

is being plotted this way:

new FunctionSeries( x => a*x*x*x + b*x*x + c*x + d, /* other stuff, spacing, number of points, etc */ )

Trigonometrical functions are done the same way:

   y = sin(3x) + 5cos(x)

is

   new FunctionSeries(x => Math.Sin(3*x) + 5*Math.Cos(x) , ....);

I would be very happy if someone could guide me in the conversion between a string (written in a textbox for example) and a call of a method that has inside the syntax shown.

EDIT: the first parameter in the FunctionSeries(a, ....) a is Func<double, double>

EDIT2: Is there a way to say to the compiler, hey, believe me "x => 5*x*x" is a Func, take it literally

something like :

Func<double, double> f = (Func<double, double>)myString;
Sturm
  • 3,968
  • 10
  • 48
  • 78
  • http://stackoverflow.com/questions/821365/how-to-convert-a-string-to-its-equivalent-expression-tree – zs2020 Sep 02 '13 at 02:24
  • [http://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net/392355#392355](http://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net/392355#392355) – Chris O Sep 02 '13 at 02:25
  • For something this simple.. NCalc is a good option. – Simon Whitehead Sep 02 '13 at 02:26
  • Thanks for the suggestions, I'll go with NCalc, if it's not too much asking Simon, could you provide me the simplest example in the world as I couldn't find my necessities in the brief documentation of NCalc. In the examples they are simply calculating the result of a expression parsed from a string. I was looking to transform the string to a Func. Do you think is that possible with NCalc? – Sturm Sep 02 '13 at 02:36

1 Answers1

0

Here I have a partial solution:

        var expresionData = new List<DataPoint>();
        Regex pattern = new Regex("[x]");

        for (int i = 0; i < 100; i++)
        {
            string a = pattern.Replace(ExpresionString, i.ToString());
            NCalc.Expression exp = new NCalc.Expression(a);
            expresionData.Add(new DataPoint(i,Double.Parse(exp.Evaluate().ToString())));
        }

I'm doing a little trick here: I transform each 'x' in the typed string to i, then I evaluate the expression and add the point. It's pretty slow. I'm still very interested in the original question:

How to transform a string to Func<double, double> (or just make the compiler take it literally).

Sturm
  • 3,968
  • 10
  • 48
  • 78