Advertisement

Polish notation calculator

Choose two operators, three numbers and the grouping. The same expression appears in all three notations, followed by its value.

Calculator

Infix
(2 + 3) * 4
Prefix (Polish)
* + 2 3 4
Postfix (reverse Polish)
2 3 + 4 *
Value
20.0000000000

Advertisement

How this calculator works

Ordinary infix notation places the operator between its operands and relies on brackets or precedence to show order. Polish notation, invented by Jan Łukasiewicz, places the operator first: + 2 3 means 2 + 3. Reverse Polish notation places it last: 2 3 +. With operators first or last and no brackets, a stack evaluates the expression by reading left to right: in postfix, push each number and, on an operator, pop two values, apply the operator and push the result.

Formula

An expression tree of root op2, left subtree (a op1 b) and right operand c has prefix op2 op1 a b c and postfix a b op1 c op2. A different grouping produces a different tree and can change the value.

Worked example

With a = 2, b = 3, c = 4 and grouping (a + b) * c, the infix form is (2 + 3) * 4, prefix is * + 2 3 4, postfix is 2 3 + 4 *, and the value is 20.

Advertisement

Frequently asked questions

Why does prefix notation need no brackets?

Each operator has a fixed number of operands, two here. Reading left to right, the structure of the expression is unambiguous, so brackets add nothing. The same is true for postfix.

Do the two groupings give different answers?

Sometimes. Addition and multiplication are associative, so (2 + 3) + 4 and 2 + (3 + 4) agree. Subtraction, division and powers do not: (8 - 3) - 2 is 3 while 8 - (3 - 2) is 7.

Where is reverse Polish notation used?

It is the basis of stack languages and many calculators, including the HP line. Commands in PostScript and the Java virtual machine also use postfix form because it maps directly onto a stack.

Can I type an arbitrary expression?

This tool takes three numbers and two operators, with a choice of grouping. That covers every shape of a three-operand expression and keeps the conversion readable; longer expressions can be built by feeding the result back in.

Sources

Advertisement