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.
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
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); Console.WriteLine(d2); Console.ReadKey(true);
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) ).
- tg(x); //tan(x)
- ctg(x). //cotan(x)
- exp(x) or e^x — exponential function;
- ln(x), (a)log(b) — (natural) logarithm;
- abs(x) — absolute of a number.
- pi — 3.14159265...;
- e — 2.71828183....
Arguments of the trigonometric functions can be expressed as radians or degrees
example (as radians):
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.
- 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)