views:

108

answers:

2

I googled and came up blank - so it's time to test the good folks at SO again! :)

Can anyone recommend an open source library (pref for .NET) that parses and calculates mathematical expressions?

e.g. input expression = "2+(n-1)*4", parameter key/value n=2, output = 6.

+1  A: 

Well, I have used IronPython for this in the past. This is actually quite a powerful route, since you can expose an API to the expressions.

On top of that, I believe that the Irony parser generator has a mathematical expression example parser. (If they don't it would be trivial to create.)

There are also plenty of Google results on this:

NCalc
.NET Math Expression Parser
Mathematical Expression Parser for .NET

Just to name a few.

John Gietzen
+4  A: 

I would take a look at NCalc. Here is a description of the project:

NCalc is a mathematical expressions evaluator in .NET. NCalc can parse any expression and evaluate the result, including static or dynamic parameters and custom functions. For additional information on the technique we used to create this framework please read this article: http://www.codeproject.com/KB/recipes/sota_expression_evaluator.aspx

If this is too complex for your purpose, you can take a look at any "parser generator" for C#. These tools allow you to specify the grammar of your expression and generate code that will parse it. Writing parser for numerica expressions should be pretty straightforward. See for example

Tomas Petricek
Thanks a ton! :)
Shaul