| home | contents | send comment | send link | add bookmark |

Reverse Polish Notation Calculator

by Stephen R. Schmitt

RPN expression:

Result:


Contents

  1. About
  2. Source code
  3. Discussion

About

This JavaScript program performs Reverse Polish arithmetic. It will accept floating point numbers and perform:

operation     operator
addition         +
subtraction      -
multiplication   *
division         /

To operate the calculator, enter an RPN expression and press the Calculate button. The calculator will parse your expression and show the result or an error message. There are two error message:

To reset the output windows, press the Clear button.

Contents


Source Code

The Java Script source code for this program can be viewed by using the View|Source command of your web browser.

You may use or modify this source code in any way you find useful, provided that you agree that the author has no warranty, obligations or liability. You must determine the suitablility of this source code for your use.

Contents


Discussion

The normal way of writing arithmetic expressions is called infix notation. Reverse Polish Notation (sometimes called postfix notation) avoids the use of parentheses in arithmetic expressions. In RPN, an operator acts on the most recent values in the expression. Some examples:

infix notation        postfix notation
 2 + 2                 2 2 +
 2 * 3                 2 3 *
 5 * (7 - 2)           5 7 2 - *
 (0 - 1) * 4 * 5       0 1 - 4 5 * *

Evaluation of postfix expressions proceeds from left to right. An arithmetic operator replaces the two numbers to the left by performing the indicated operation. For example:

 7  10  5  /  +  6  2  *  + 
 7  2  +  6  2  *  +

 7  2  +  6  2  *  +
 9  6  2  *  +

 9  6  2  *  +
 9  12  +

 9  12  +
 21 

This calculator evaluates postfix expressions using a stack. The following rules are used:

Contents


AbCd Classics - free on-line books


Copyright © 2004, Stephen R. Schmitt