0

Possible Duplicate:
Is there a string math evaluator in .NET?

I need to implement mathematical expression parser. It has to evaluate the following expressions:

  • Basic operators(+,-,*,/,%[modulo operator])
  • priority operations such as 2*(4-1)
  • sin,cos,tan,cotan, log(base,number) functions
  • allows compositions such as sin(cos(log(2,32)))
  • power operation such as 2^5

First that I wanted to use JScript eval function. But it's not unsafe and no power operator. Secondary I searched for some libraries in Internet. But as turned out, I cannot use them. So the question is the following: how safe is JScript eval function calling and are there any standard .net tools for my task? If not, which algorithm is the best? As of now I'm trying to build expression tree and then compile it to get result.

Community
  • 1
  • 1
seeker
  • 3,255
  • 7
  • 36
  • 68
  • Just use JavaScript. The power is Math.pow(). – Seva Alekseyev Jul 21 '12 at 14:48
  • @SevaAlekseyev I suspect using JScript eval is not safe because you can evaluate virtually any command. – seeker Jul 21 '12 at 14:50
  • 1
    Actually, evaluating mathematical expressions is a fairly standard "textbook example" to take a first step into compilers: everyone knows them, they are not complicated, and its immediately useful. A bit of searching around the net should produce a few descriptions of recursive-descent parsing with a calculator example; once you grasp the basic concept it shouldn't be difficult to add more operators and functions. – Christian Stieber Jul 21 '12 at 14:56
  • If you want to simply find an existing library to use, check out FLEE: http://flee.codeplex.com/ – Chris Sinclair Jul 21 '12 at 15:20
  • Looks very similar to http://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net and http://stackoverflow.com/questions/1437964/best-and-shortest-way-to-evaluate-mathematical-expressions – Mathias Jul 21 '12 at 15:48

2 Answers2

1

You can try NCalc

Dictionary<string, int> dict = new Dictionary<string, int>() {
    {"a",1} ,
    {"b",4}
};

NCalc.Expression exp = new NCalc.Expression("a + b / 2 * myfunc(3.14)");

exp.EvaluateFunction += (s, e) =>
    {
        var d = (double)e.Parameters[0].Evaluate();
        e.Result = Math.Cos(d);
    };

exp.EvaluateParameter += (s, e) =>
    {
        e.Result = dict[s];
    };

var result = exp.Evaluate();
L.B
  • 114,136
  • 19
  • 178
  • 224
0

Or jep.net - disclaimer: i am the author.