Click here to Skip to main content
Click here to Skip to main content

Math Parser .NET C#

By , 27 Mar 2013
 

Introduction   

This is light, fast and simple to understand mathematical parser designed in one class, which receives as input a mathematical expression (System.String) and returns the output value (System.Double). For example, if you input string is "√(625)+25*(3/3)" then parser return double value — 50. 

Background  

The idea was to create a string calculator from educational goals.  

How it work  

 

More look in the code, I tried to explain the work of the parser code in the comments and how it can be changed and extended. 

Convert to RPN:

* Input operators are replaced by the corresponding token (its necessary to distinguish unary from binary). 

Using the code  

Example:   

    public static void Main()
    {     
            MathParser parser = new MathParser();
	    string s1 = "pi+5*5+5*3-5*5-5*3+1E1";
	    string s2 = "sin(cos(tg(sh(ch(th(100))))))";
            bool isRadians = false;
            double d1 = parser.Parse(s1, isRadians);
	    double d2 = parser.Parse(s2, isRadians);

            Console.WriteLine(d1); // 13.141592...
	    Console.WriteLine(d2); // 0.0174524023974442
            Console.ReadKey(true); 
    } 

Features  

Ariphmetical operators :

  • () — parenthesis; 
  • + —  plus (a + b); 
  • - — minus (a - b); 
  • * — multiplycation symbol (a * b); 
  • / — divide symbol (a / b); 
  • ^ — degree symbol (a ^ b); 
  • √(), sqrt() — square root ( √(a) ). 

Functions 

Trigonometric functions: 

  • sin(x);
  • cos(x);
  • tg(x); //tan(x) 
  • ctg(x). //cotan(x) 

Hyperbolic functions:

  • sh(x);
  • ch(x);
  • th(x).  

Other functions: 
  • exp(x) or e^x — exponential function;  
  • ln(x), (a)log(b) — (natural) logarithm;
  • abs(x) — absolute of a number.  

Constants:

  • pi — 3.14159265...;  
  • e — 2.71828183....  

Arguments of the trigonometric functions can be expressed as radians or degrees
example (as radians):  

parser.Parse(s, true);

Work with any char decimal separator in real number (regional settings).

New operators, functions and constants can be easily added to the code. 

This parser is very basic (special designed in 1 file such class), convenient for the further implementation, expansion and modification.      

Points of Interest     

I better understand the parsers and learned about the reverse-polish notation.

History

  • 2012/05/09: released the source code (1_0); 
  • 2012/05/15: optimized and modified code (1_1); 
  • 2012/06/07: optimized parser (1_2); 
  • 2012/09/11: some refactoring in code, added unit tests (1_2a); 
  • 2012/12/02: improved code (1_2b). 
  • 2013/01/27: improved code (1_3) 

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

kirnbas
Kazakstan Kazakstan
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberFlorian Rappl29 Aug '12 - 8:50 
GeneralRe: My vote of 4memberkirnbas29 Aug '12 - 19:34 
GeneralRe: My vote of 4memberFlorian Rappl29 Aug '12 - 21:27 
GeneralRe: My vote of 4memberAndreas Gieriet27 Jan '13 - 8:19 
AnswerCodememberClifford Nelson24 Aug '12 - 7:07 
GeneralRe: Codememberkirnbas24 Aug '12 - 7:46 
NewsSymmemberWarren Harding16 Aug '12 - 20:32 
GeneralRe: Symmemberkirnbas24 Aug '12 - 6:19 
QuestionBroken Image linksmemberMarcus Kramer7 Jun '12 - 4:53 
AnswerRe: Broken Image linksmemberkirnbas7 Jun '12 - 5:32 
GeneralPlease show and explain the codememberPIEBALDconsult14 May '12 - 13:51 
GeneralRe: Please show and explain the codememberkirnbas15 May '12 - 2:22 
GeneralRe: Please show and explain the codememberPIEBALDconsult15 May '12 - 7:03 
SuggestionQuite complicated expression evaluator...memberAndreas Gieriet14 May '12 - 12:18 
Hello kirnbas,
 
your evaluator solution seems to me quite verbose and over-complicated.
You might have a look at Mathematical Expression Parser Using Coco/R[^] which provides two solutions:
A) writing a similar evaluator in about 100 lines of code by using http://ssw.jku.at/Coco/[^]
B) writing the same evaluator, but hand crafted, in less than 150 lines of code
 
BTW: I also find that you should elaborate more on why you show us your trick - why should I red that? E.g. if talking about localized number scheme, then you must talk about the consequences and how you deal with these:
- What number formats exist (decimal point, thousand separator, ...)?
- How you deal with the ambiguities (you have to also localize the list separator)?
- Run the localization on kk-KZ, ky-KZ, en-US, de-DE, de-CH, sv-SE, sv-FI
 
The quirks on localization is that the coma is usually used as list separator (e.g. f(a,b)) as well as thousand separator (en-US) or as decimal separator (de-DE).
 
One approach is to allow the ambiguity and let the parser read greedily (letting the user to solve ambiguities by adding parenthesis, e.g. f((3,14159),(1,4142135))).
Another approach is to make the language not ambiguous and also take the list separator from the CultureInfo class (beside the thousand separator and the decimal separator).
 
At least this topic is worth an elaboration. That's why my vote of 3.
 
Cheers
Andi
QuestionYou might want to elaborate on some of the inner workings, etc.memberednrg14 May '12 - 8:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 28 Mar 2013
Article Copyright 2012 by kirnbas
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid