How can I evaluate an expression using sin, cos and other functions?

After some research, I learned about postfix notation and how to parse an expression.

My code converts to postfix notation and then evaluates it using a stack based method. For example:

Initial expression: 5 + 2^(4 - 1)
Postfix notation: 5 2 4 1 - ^ + 
Result: 13


Now I'm trying to expand this program to be able to evaluate expressions with functions such as sin, cos, log, for example 5 + sin (2 + log (2))

. My initial idea was that before parsing it, find these functions, evaluate their results, and replace them in a string. But I don't think this is a very good idea ...

So how can I do this in an efficient way?

Here is the code written in C # if used: , but I would prefer some pseudocode, so I understand that I write better ... I'm not the kind of guy to just copy and insert.


source to share

1 answer

Treat these functions as you would any other operator, as well as curly braces. Calculate what's in curly braces first, then execute the function.

Initial: 3 * Sin(4 + 5)
Postfix: 4 5 + Sin 3 *       (that how I would enter it in a HP calculator)
or:      3 4 5 + Sin *


Except +

which consumes two numbers, Sin

consumes only one number.



All Articles