Parse mathematical expressions
I need to parse mathematical expressions,so that the user can enter "2*2+4 instead of just 8.The user should also be able to use variables,so if the user sets the variable X to 4,2*2+X would also be 8.I also need to support some simple math functions like Tan,Cos and Sin.I was wondering if there was already a function/library which can do this,if so,could you post the link to some tutorials/documentation on this?
Btw,I need this to work under Linux,and preferable also on other OS'.
Thanks in advance.
Re: Parse mathematical expressions
Quote:
I need to parse mathematical expressions,so that the user can enter "2*2+4 instead of just 8.The user should also be able to use variables,so if the user sets the variable X to 4,2*2+X would also be 8
Search internet for INFIX and POSTFIX algorithms or pseudo algorithms.
It's quite simple do a *basic* expression parser:
- first
You should convert infix expression (eg. 2 * sin(3)) into postfix notation ( 2 3 sin * )
- second
You can "pop" each simbol from the stack and evaluate it.
see for example:
Good luck :)