hello all
hello all

Reputation: 252

Interpreting a mathematical expression in Reverse Polish Notation (Postfix Notation)

I've found a way to convert a math expression in infix notation into postfix notation. (http://en.wikipedia.org/wiki/Shunting-yard_algorithm) But then, how should I code to interpret the result expression?

Here's my idea:

For operand-only expressions:

  1. Look for a set of objects that follow the format operand-operand-operator.
  2. Apply the rules of calculation of the operator to the two operands.
  3. Swap the set of objects into one operand which is the result of the calculation.

For expressions with functions (sine, absolute value, signum...)

  1. Look for a set of objects that follow the format operand-operand-...-operator.
    • The number of operands depends on how many parameters are needed to pass into the function. For example:
      • sine - one parameter (the acute angle)
      • power - two parameter (n th power of number m)
      • 3x3 matrix - nine parameters
  2. Do whatever else I mentioned above.

I'm now in a situation that I have not any environment to implement my ideas into a piece of code, thus I can only talk abstract.

Is this idea possible or not? If there can be improvements, please note them. References are also welcomed.

If you are presenting a piece of code, please change the code into words that everyone can understand. For example:

Change:

for (var i:int = 0; i < rpn.length; i++) {
    if ("1234567890.".indexOf(rpn[i]) != -1) {
        // do something...
    }
}

Into:

for every element in the postfix result,
    if the element is a number,
        do something...
    end if
end for

end ... is optional, though.

Thanks!

Upvotes: 0

Views: 1791

Answers (1)

David Z
David Z

Reputation: 131550

Usually this is the easy part... you just traverse your postfix expression from left to right. Each time you encounter a number, you push it on a stack. Each time you encounter an operator, you pop the relevant number of operands off the stack, compute the result, and push it on the stack.

Upvotes: 4

Related Questions