2

I've got the shunting yard algorithm implemented (using code from wikipedia, modified to use stl stacks/queues), but now I'm wondering how it's going to evaluate decimals that I get from division. The javascript app at scriptasylum.com (can't link) works just fine and gives the expected output:

Infix: 1/6*((1/4)/(1/2)+1/2)
Postfix: 16/14/12//12/+*
Eval: 0.16666666666666666 (1/6)

Infix: 0.5+1
Postfix: 0.51+
Eval: 1.5

I found one example of postfix evaluation on here, but it wasn't finished and didn't account for decimal points.

Here's my current code: http://codepad.org/zDXnOELK

Manishearth
  • 14,882
  • 8
  • 59
  • 76
s00pcan
  • 163
  • 1
  • 2
  • 9

1 Answers1

2

The easy thing (which is what the Javascript impl is doing, by virtue of the language semantics) is to represent all numbers internally as double.

If you want to do something cleverer, I gotta warn you that it's a lot more code and a lot more hard design decisions, and I recommend you start by reading up on the Scheme numeric tower.

zwol
  • 135,547
  • 38
  • 252
  • 361
  • How does it tell the difference between 10.51+0.5 and 10.5+10.5? Both evaluate to 10.510.5+ – s00pcan Nov 17 '10 at 21:37
  • You should be emitting a space after each token, otherwise yes, it's ambiguous. (In other words, evaluate `10.51+0.5` to `10.51 0.5 +` and `10.5+10.5` to `10.5 10.5 +`.) Also, I can't find the thing you're comparing against, but it may be directly evaluating the parse tree rather than serializing to postfix first. – zwol Nov 17 '10 at 22:05
  • s00pcan: Your problem has nothing to do with decimals and everything to do with having more than one digit in an operand. – Ben Voigt Nov 17 '10 at 22:22
  • I realize that. What can I do about it? Should I switch this stack to use strings or doubles instead of single chars, then read up until the next operator and then push it to the stack? – s00pcan Nov 17 '10 at 22:42
  • Yeah, that sounds about right. (Operator or whitespace.) `strtod` is your friend. – zwol Nov 17 '10 at 22:47
  • Modified the code to use a stack of strings for now. Not sure if that's what I want yet. But it makes it easier to have the operators in there with the numbers. infix: 1.0/60 postfix: 1.0 60 / – s00pcan Nov 17 '10 at 23:01
  • Ultimately you may want `stack` where `Term` is a class that can represent either an operator code or an operand. – zwol Nov 17 '10 at 23:38
  • Right now I have it basically working with operators over one digit and with decimal points. It gets tripped up by the parenthesis, but I'm going to work on that some more. – s00pcan Nov 18 '10 at 00:12