In this article, I will at first discuss about Polish notation then how it can be used to make better calculator.
Polish Notation: Polish notation is named after Polish mathematician Jan Lukasiewiez. This is a notation where operator symbol is placed before its two operands. Example +CD, /AB which can be normally written as C+D, A/B. The question is why I should use Polish notation. I am not disgusted about my familiar infix notation! The answer is very simple. Infix notation is familiar to me but not to computer. When we write complex expression such as
It’s very much difficult to evaluate the expression for a computer. Uses of parenthesis become more difficult to evaluate the expression. But in polish notation, it can be written as:
A B C * D E F ^ / G * - H * +
Evaluation is simple, just scan through the expression, if an operator comes, pick up last two operands, execute operation then put back the result. At last what you have is the result. (Actually this is not Polish notation, rather anti-Polish notation which can be expressed as CD+, AB/. Because this is more effective to use with a much known data structure, stack).
Using This: Creating reusable program is the striking feature of dot Net programming or Object Oriented Programming. So I’ve created a class library project named MathEval such that I can use it whenever I needed it and I can also distribute it to others so that they can take the advantage of it.
Here I’ve created a public function TextToValue which takes a string as argument and return its corresponding value in double format.
Problems I faced: In this program, I’ve tried to evaluate our familiar infix expression to postfix and then evaluate. To format the string as a sequence of operators and operands is a problem. Because, operands can be of variable length. For this reason, whenever I faces a character that can contribute to make an operand, I’ve go through until I faces a character that can’t be included in operand making.
The next problem is, we generally use unary minus to make an expression. But how can I distinguish unary minus from binary minus? I’ve found that in a general expression written in infix notation, the unary minus can be in the first place of the expression or right after a binary operator. So I’ve kept track whether the minus to be a unary or binary by using a Boolean variable canUnaryMinus.
As I’ve used factorial operation, there is some length tradeoff. I’ve seen that in a double variable, factorial bigger then 170 produces a ResultOutOfRange exception. So if it is factorial expression, the value should be checked not to be bigger then 170. The biggest factorial determined by my calculator is 7.25741561530799E+306.
The source code is public, but I want to track who are interested in code. So if you want to get code to have a look or modify it or even create a batter one, mail me at email@example.com .
The application file may not work if you haven’t .Netframework 3.0 installed.