What is the best way to evaluate mathematical expr

2019-01-04 08:56发布

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!

11条回答
倾城 Initia
2楼-- · 2019-01-04 09:22

While searching a library for a similar task I found libmatheval. Seems to be a proper thing. Unfortunately, GPL, which is unacceptable for me.

查看更多
疯言疯语
3楼-- · 2019-01-04 09:25

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;
}
查看更多
老娘就宠你
4楼-- · 2019-01-04 09:26

I have developed a simple expression parser in C++ and Java. At the moment they only handle arithmetic operators +. -, / * but there is no reason they could not be extended to accommodate more functions.

These simple examples use the shunting yard algorithm to convert the expressions into reverse Polish notation and then another simple stack-based algorithm to actually evaulate the expression.

Code samples can be found here.

查看更多
做自己的国王
5楼-- · 2019-01-04 09:32

I've written a simple, easy-to-use, front-end to Lua for evaluating arithmetic expressions from C (and C++ of course). See http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#ae . See also OpenSouce C/C++ Math expression parser Library and What is a fast C or Objective-C math parser?

查看更多
Emotional °昔
6楼-- · 2019-01-04 09:35

Boost.Spirit is a C++ parser library.

Examples:

查看更多
登录 后发表回答