Search code examples
c#.netparsingopen-source

Open source mathematical expression parser?


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.


Solution

  • 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