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

camino picture camino · Feb 25, 2011 · Viewed 19.2k times · Source

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!

Answer

user5374653 picture user5374653 · Sep 29, 2015

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;
}