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 your input string is "√(625)+25*(3/3)" then parser returns double value — 50.
Background
The idea was to create a string calculator for educational goals.
How it work
For more please look at the code, I tried to explain the work of the parser 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);
Console.WriteLine(d2);
Console.ReadKey(true);
}
Features
Ariphmetical operators :
- () — parentheses;
- + — plus (a + b);
- - — minus (a - b);
- * — multiplycation symbol (a * b);
- / — divide symbol (a / b);
- ^ — degree symbol (a ^ b).
Functions :
Trigonometric functions:
- sin(x);
- cos(x);
- tg(x);
- ctg(x).
Hyperbolic functions:
Other functions:
- √(a), sqrt(a) — square root of a number;
- exp(x) — exponential function (or just use e^x);
- (a)log(b) — logarithm;
- ln(x) — natural logarithm;
- abs(x) — absolute value.
Constants:
- pi — 3.14159265...;
- e — 2.71828183....
Arguments of the trigonometric functions can be expressed as radians (true) or degrees (false) by sending appropriate bool value to parse method. Example (as radians):
parser.Parse("sin(90)", 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 simple (special designed in single class), convenient for the further implementation, expansion and modification.
Points of Interest
I better understand how parsers work and learned about the reverse-polish notation.
History
- 2012/05/09: released the source code (1_0);
- 2012/06/07: optimized parser (1_2);
- 2014/02/28: rewritten version (1_4).