Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding what to do with output of shunting-yard algorithm

I've been looking at the wiki page: http://en.wikipedia.org/wiki/Shunting-yard_algorithm

I've used the code example to build the first part, basically I can currently turn :

3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 into 3 4 2 * 1 5 − 2 3 ^ ^ / +

But I don't know how to then use 3 4 2 * 1 5 − 2 3 ^ ^ / + to obtain 3.00012207

And the example code and explanation on wiki aren't making any sense to me.

Could someone please explain how to evaluate 3 4 2 * 1 5 − 2 3 ^ ^ / + and produce the answer. Thanks in advance. I don't need a code example just a good explanation or a breakdown of an example.

Not that it matters but I am working .net C#.

like image 495
Patrick Lorio Avatar asked Dec 01 '11 16:12

Patrick Lorio


1 Answers

The purpose of the shunting yard algorithm is that its output is in Reverse Polish Notation, which is straightforward to evaluate:

  • create a stack to hold values
  • while there is reverse polish notation input left:
    • read an item of input
    • if it is a value, push it onto the stack
    • otherwise, it is an operation; pop values from the stack, perform the operation on those values, push the result back
  • when there's no input left, if the expression was well formed, there should be exactly one value on the stack; this is the evaluated result.
like image 189
moonshadow Avatar answered Sep 16 '22 18:09

moonshadow