![]() |
Languages »
C / C++ Language »
General
Intermediate
Expression evaluator : using RPNBy lallousAn article showing how to evaluate mathematical expressions using reverse polish notation (RPN) |
VC6, Windows, Dev
|
|
|
|
||||||||||||||||
This article will demonstrate how to evaluate complex mathematical expressions by converting them from infix notation to postfix notation and evaluating the expression. In the process we will be using STL's stack and string classes. When finished, the program should be able to evaluate expressions such as:
expr = "(12232+(43*43-(250/(3*8))*44)/12-311) * (5==5)"
Most programming languages require that you enter expressions in infix notation that is: operators and operands are intermixed, example: "5*6-3*2*3".
The postfix notation, introduced in 1950 by the Polish logician Jan Lukasiewicz, is a method of representing an expression without using parenthesis and still conserving the precedence rules of the original expression. For example, the previous expression could have been written like: "5 6 * 3 2 * 3 * -"
Here's is how to convert from an infix notation to postfix notation:
Now evaluating a postfix (RPN) expression is even easier:
#include <iostream.h> #include <string> #include "ExpressionEvaluator.h" using std::string; int main() { long result; double resultdbl; int err; string s; s = "1+2*(1-2-3-4)"; err = ExpressionEvaluator::calculateLong(s, result); if (err != ExpressionEvaluator::eval_ok) cout << "Error while evaluating!" << endl; else cout << "Evaluation of (int):" << s.c_str() << " yielded: " << result << endl; s = "1.1/5.5+99-(4.1*(2+1)-5)"; err = ExpressionEvaluator::calculateDouble(s, resultdbl); if (err != ExpressionEvaluator::eval_ok) cout << "Error while evaluating!" << endl; else cout << "Evaluation of (double):" << s.c_str() << " yielded: " << resultdbl << endl; return 0; }
This code can be extended to allow you perform other operations, however they must be binary operation (takes two operands). To extended the code simply add a new operator into the "operators" array along with its precedence value. If you introduce a new symbol make sure you add the symbol into the "operators[0]" string too. Precedence is important for generating a proper postfix expression. After adding a new operator, define its behaviour in the "evaluateRPN" function as:
if (token == "PUT YOUR OPERATOR SYMBOL HERE") r = doMyOperation(op1, op2);
Hope you find this code and article useful.
isOperator()
49 messages have been posted for this article.
Visit http://www.codeproject.com/KB/cpp/rpnexpressionevaluator.aspx to post and view comments
on this article, or click
here to get a
print view with messages.
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 5 Nov 2003 Editor: Nishant Sivakumar |
Copyright 2003 by lallous Everything else Copyright © CodeProject, 1999-2010 Web22 | Advertise on the Code Project |