What is the best way to evaluate mathematical expressions in C++?

Solution 1:

Not sure why 'pow' only has one parameter, but using the ExprTk library one can derive the following simple solution:

#include <cstdio>
#include <string>
#include "exprtk.hpp"

int main()
{
   typedef exprtk::expression<double> expression_t;
   typedef exprtk::parser<double>         parser_t;

   std::string expression_string = "3 + sqrt(5) + pow(3,2) + log(5)";

   expression_t expression;

   parser_t parser;

   if (parser.compile(expression_string,expression))
   {
     double result = expression.value();

     printf("Result: %19.15\n",result);
   }
   else
     printf("Error in expression\n.");

   return 0;
}

Solution 2:

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 GNU bison tools, which can build powerful parsers for these sorts of expressions. I believe that the bison documentation even shows you how to parse and evaluate arithmetic expressions, so you might have your work already done for you.

Hope this helps!