Skip to main content
gamedev.net
🔒 Locked

Math Parser

Started by Kranar 4 replies 300+ views
Original Post
Kranar
Kranar
I searched Yahoo for a C++ Math Parser and all I could find was UCalc Math Parser. I gave it a shot but it seems way too advanced for what I need it for, and thus it also runs WAY too slow for what I need it for as well. Anyone know of a similar library, all it needs is one simple function that takes in a string, like "5.5 + 2.3 - (3*2 + 1) / 6" and returns a double as the answer, 6.633333. Addition, subtraction, multiplication, division, and brackets are the only operations I need it to evaluate.
Radan
Radan
Its not that dificult.

just precompile the expressions into Polish notation and parse that. Its gonna be amaizingly fast.
-----------------Always look on the bright side of Life!
Kranar
Kranar
Exactly what I was looking for, thank you.
Kranar
Kranar
Okay this reverse polish notation is pretty interesting, although I must say a bit confusing.

See, the way I see it, I should parse the following:

5*2 + 6*5 + 8 / 2

Into the following:

5 2 6 5 8 2 * * / + +

Going from left to right, and then setting * and / to have higher precedence than +.

But for whatever reason, when I evaluate that on paper, it just doesn''t work. The steps are this:

Evaluate 8 * 2

5 2 6 5 16 * / + +

Evaluate 5 * 16

5 2 6 80 / + +

Evaluate 6 / 80

5 2 0.075 + +

Evaluate 2 + 0.075

5 2.075 +

Evaluate 5 + 2.075

7.075

The real answer though is:

44

Where did I go wrong?
eighty
eighty
You should''ve written it like this:
5 2 * 6 5 * + 8 2 / +

Think of each operator as a function. Then 8*8 is *(8,8). Then you can rewrite your original expression like this:
5*2 + 6*5 + 8 / 2
+(+(*(5,2),*(6,5)),/(8,2))

Place the operators to the right of the their arguments and remove the parantheses and commas and you have
52*65*+82/+

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.