views:

112

answers:

5

I need something to embed in my C/C++ program to interpret formulas of the like x*log(x) or sin(x). I would like something small and simple, otherwise I can just embed Python, or Ch, or Scheme, or you name it. But all I need is simple formulas. I have searched the web without luck. Although I don't require it, performance (e.g., the use of a simple JIT) would be a bonus.

+4  A: 

An excellent portable language for this sort of thing is JavaScript. There are more than a few implementations to choose from, for C and C++ there are at least:

Another easily embeddable choice might be Lua. It's certainly easier to use something that already exists rather than reinventing an expression parser.

Greg Hewgill
+3  A: 

Use Reverse Polish notation. There are few algorithms:
1. Parse equation and convert to infix notation (that is easy, you simply identify chain of symbols)
2. Using Dijkstra's shunting-yard algorithm convert infix to RPN.
3. Using DFS calculate the expression

I'm sure there is a lot implementations on the net. I even wrote my own few years ago (without functions feature).

adf88
+4  A: 

Lua - is by far the simplest to embed and use and there is a very small and very fast version with a JIT: http://luajit.org/

Luther Blissett
I have successfully assimilated luajit in my code now. Although I needed a couple of hours for figuring out that luaL_loadbuffer needs a luaL_pcall after it....other than that it works o.k.
dignor.sign
Cool! Good luck with your project!
Luther Blissett
A: 

FFmpeg has a very nice one which you should check out.

R..
A: 

What about writing your own simple stack-machine for calculating such formulas?

MInner