Interprete/calculate arithmetic expression

  • Thread starter Thread starter frankh
  • Start date Start date
F

frankh

Got earlier very valuable feedback from this group, so I am trying
again.

Given a string with an arithmetic expression containing variables, e.g.
"a+b*sin(x)", how can I calculate its value within my program for given
variable values? (Think of the string as a user input.) Is there an
easier way than writing an interpreter myself? Mathematical notation is
preferred, but C# syntax ("Sin" instead of "sin") would be acceptable
too.
 
You could use a compiler compiler like ANTLR (http://www.antlr.org)
which can output the C# code for you if you're familar with writing
EBNF grammars.

I suppose reflection is always a possibility, but I wouldn't go in that
direction for several reasons.

Honestly, writing the interpreter yourself might be the best option.
It's actually pretty easy for mathematical expressions. It involes 3
major steps. First, tokenize the expression so that it is easier to
work with. Next, convert infix notation to postfix notation. This is
the hardest part. Postfix notation is nice though because you don't
have to worry about parenthesis or complex operator precedence and
associativity rules during the evaluation step. Finally, evaluate the
postfix expression. This is easiest part. Scan tokens from left to
right. Push operands onto a stack. Pop enough operands from the stack
to apply any operators you see and then push the result back onto the
stack. The last value on the stack is the result.

Brian
 
There was an article on codeproject explaining how to write an interpreter
using dynamic code compilation but it got moved / removed, so try google
cache

Please note that this is a very insecure method as user can type a
"mathematical" expression like "System.Diagnostics.Process.Start(new
System.Diagnostics.ProcessStartInfo("format", "d: /autotest")).Handle;"
(.Handle because the solution I have posted requires the expression to
return float :-)

which could be quite harmful..

google cache link
http://66.249.93.104/search?q=cache...site:codeproject.com+csharpcodeprovider&hl=en
 
I wrote a parser in C# that you could modify to parse your expressions. It
is only about 200 statements (plus a library you do not have to modify).
However, it uses generics, so you need C# version 2. It is well documented,
and the source code is at:
http://www.frontiernet.net/~fredm/dps/Contents.htm

See Chapter 3 for the parser.

You would need to build the tokenizer, but the Regex class can do that
pretty easily for you.
 
Fred,

Great link. I see you have an interest in game trees as well. That is
an interest of mine as well.

Brian
 
Back
Top