3

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)

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?

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.

4
  • I did Google the question as a comment in the linked question suggests, it led me back to Stack Overflow. Commented Sep 1, 2015 at 13:38
  • 1
    Maybe helpful? msdn.microsoft.com/en-us/library/… Commented Sep 1, 2015 at 13:44
  • have you tried: c-sharpcorner.com/UploadFile/mgold/… or ncalc.codeplex.com? Commented Sep 1, 2015 at 13:46
  • 1
    You need a parser/lexer for mathematical expressions. Commented Sep 1, 2015 at 14:27

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.