在C++中评估数学表达式的最佳方法是什么?

cam*_*ino 31 c++ math expression

例如,评估任何自定义数学表达式的最佳方法是什么

3+sqrt(5)+pow(3)+log(5)
Run Code Online (Sandbox Code Playgroud)

我知道将Python嵌入到C++中可以做到这一点; 有没有更好的方法?

谢谢!

小智 19

不确定为什么'pow'只有一个参数,但使用ExprTk库可以得到以下简单的解决方案:

#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;
}
Run Code Online (Sandbox Code Playgroud)


aaz*_*aaz 3

Boost.Spirit是一个 C++ 解析器库。

例子: