Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

Code Snippets / [DBP] Shunting Yard algorithm

Author
Message
Sven B
19
Years of Service
User Offline
Joined: 5th Jan 2005
Location: Belgium
Posted: 24th Oct 2010 12:44
Hello,

Here is a simplified version of the Shunting Yard algorithm, used to convert a mathematical expression in infix notation to RPN (Reverse Polish Notation).

To make the code more readable, I didn't include support for variables or numbers of more than one character, and I also left out functions. I hope the idea behind the algorithm is visible though.



The great thing about this algorithm is that it's of the order O(n). Each character of the infix expression is only read once.

Cheers!
Sven B

Neuro Fuzzy
16
Years of Service
User Offline
Joined: 11th Jun 2007
Location:
Posted: 26th Oct 2010 10:18
Woah, that's really cool, I had no idea about reverse polish notation.

If you wanted to evaluate the notation, would you just parse from left to right until you found an operator, evaluate
operator(value 2 spaces before the operator, value 1 space before the operator)
to a single value, and then re-evaluate the notation? (recursive)

Also, are there any benefits to using RPN as far as optimization of equations goes?

Sven B
19
Years of Service
User Offline
Joined: 5th Jan 2005
Location: Belgium
Posted: 26th Oct 2010 17:26
Hi,

First of all, thanks ^^.

Quote: "If you wanted to evaluate the notation, would you just parse from left to right until you found an operator, evaluate
operator(value 2 spaces before the operator, value 1 space before the operator)
to a single value, and then re-evaluate the notation? (recursive)"


Actually, yeah!

To evaluate the notation, you just read it from left to right on a stack-based manner: (pseudo)



As you can see, this is a very simple algorithm, and also very fast on a computer. You can easily see there's no searching necessary to find parentheses for example. It isn't a coincidence that this evaluation algorithm is pretty much what the computer does on machine level. The compiler uses a (probably modified) version of the Shunting Yard algorithm to convert the infix expressions to assembly/machine code.

I have no idea on how this affects equation optimization though.

Cheers!
Sven B

Phaelax
DBPro Master
21
Years of Service
User Offline
Joined: 16th Apr 2003
Location: Metropia
Posted: 8th Nov 2010 07:42
As far as human readability, RPN looks more confusing. I understand it, but simple equations make me think harder.

Your signature has been erased by a mod please reduce it to 600 x 120.

Login to post a reply

Server time is: 2024-04-19 15:58:29
Your offset time is: 2024-04-19 15:58:29