What is the best way to evaluate any custom math expression, for example
3+sqrt(5)+pow(3)+log(5)
I know that embedding Python into C++ can do that; is there any better way?
Thanks!
What is the best way to evaluate any custom math expression, for example
3+sqrt(5)+pow(3)+log(5)
I know that embedding Python into C++ can do that; is there any better way?
Thanks!
Format a string like this:
Invoke the C++ compiler to compile the above code into a shared library. Then load that shared library, resolve the address of
evaluate
, invoke it and get the result.Lepton is another C++ library that can do this. In addition to parsing and evaluating expressions, it also has some more advanced abilities. For example, it can compute analytic derivatives, and it can do some basic algebraic simplification of expressions. The library is quite small, and it's open source (MIT license).
Here's an approach written for recent versions of Boost Spirit: http://agentzlerich.blogspot.com/2011/06/using-boost-spirit-21-to-evaluate.html
There is no way to do this with an off-the-shelf standard library in C++, though there are many good parsing algorithms out there that will let you evaluate expressions like these.
If you'd like some references on good parsing algorithms, consider looking into Chapter 14 on expression parsing in Programming Abstractions in C++ (free and available online!), or consider looking into Dijkstra's shunting-yard algorithm. Both of the algorithms mentioned here are simple to implement and will let you evaluate expressions with relative ease.
If you're interested in some more hardcore tools for evaluating expressions, consider looking into the
flex
and GNUbison
tools, which can build powerful parsers for these sorts of expressions. I believe that thebison
documentation even shows you how to parse and evaluate arithmetic expressions, so you might have your work already done for you.Hope this helps!
The easiest way is to use an external library. The easiest one I've found is TinyExpr. It's written in C, so it should be very easy to call from C++. Also, it's only one source file and one header file. Very easy to integrate. You can get it here.
Solving your example problem is just:
You could do that, but you'd be pulling in a huge dependency to solve a simple problem.
muParserX is another C++ mathematical expression parser.