Understanding the Polish notation converter — concept and principle
This converter turns an arithmetic expression between infix (the usual form), prefix (Polish) and postfix (reverse Polish) notation, evaluates it, and lists the operations in the order a stack would perform them. Use it for computer science courses, compiler and calculator programming, RPN calculators and checking order of operations.
How it is calculated
- Infix input is parsed with the usual precedence: ^ first (right to left), then × and ÷, then + and − (left to right). A minus sign directly before a number is read as a negative number.
- Postfix writes each operator after its two operands; prefix writes it before them.
- Evaluation uses a stack: read postfix left to right, push numbers, and at each operator pop two values (the first popped is the right operand), apply the operator and push the result. Prefix is evaluated the same way reading right to left.
- The infix result is written with only the brackets that are needed.
The principle
Infix notation needs precedence rules and brackets to say which operation comes first. Jan Łukasiewicz showed that placing every operator before its operands removes the need for brackets entirely, because each operator always takes the next two complete expressions. Postfix does the same with operators after operands, and it matches how a stack machine works: numbers wait on the stack until an operator uses them. That is why many compilers convert expressions to postfix and why some calculators use RPN.
Worked example
Default input: infix (3 + 4) × 5 − 6 ÷ 2.
- Prefix: − × + 3 4 5 ÷ 6 2.
- Postfix: 3 4 + 5 × 6 2 ÷ −.
- Stack evaluation: 3 + 4 = 7; 7 × 5 = 35; 6 ÷ 2 = 3; 35 − 3 = 32.
- Value = 32, using 4 operators.
How to read the result
Read prefix as "apply this operator to the next two things": − (× (+ 3 4) 5) (÷ 6 2). The operation list shows exactly the order in which a computer would evaluate the expression. If the value differs from what you expected, the precedence in your infix expression is probably not what you intended.
Common mistakes
- Reversing the operands of − or ÷ when popping from the stack; the first value popped is the right operand.
- Treating 2 ^ 3 ^ 2 as (2 ^ 3) ^ 2; powers group right to left, giving 2 ^ 9 = 512.
- Forgetting spaces between multi-digit numbers in postfix, so 3 4 becomes 34.
- Confusing a negative number with the subtraction operator.
Frequently asked questions
Why is it called Polish notation?
It was introduced by the Polish logician Jan Łukasiewicz in the 1920s.
Does postfix ever need brackets?
No. The order of tokens alone fixes the order of operations.
Is prefix the reverse of postfix?
Not in general. Reversing a postfix string also swaps the operand order, so it is not the same as prefix.
Sources: Weisstein, E. W., "Reverse Polish Notation", Wolfram MathWorld