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条回答
冷血范
2楼-- · 2019-01-04 09:11

Format a string like this:

#include <boost/lexical_cast.hpp>
#include <string>
#include <math.h>

extern "C" {
std::string evaluate() { return boost::lexical_cast<std::string>(3+sqrt(5)+pow(3)+log(5)); }
}

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.

查看更多
我命由我不由天
3楼-- · 2019-01-04 09:14

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).

查看更多
女痞
4楼-- · 2019-01-04 09:14

Here's an approach written for recent versions of Boost Spirit: http://agentzlerich.blogspot.com/2011/06/using-boost-spirit-21-to-evaluate.html

查看更多
Bombasti
5楼-- · 2019-01-04 09:16

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!

查看更多
劳资没心,怎么记你
6楼-- · 2019-01-04 09:20

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:

#include "tinyexpr.h"
#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Result: %f\n", te_interp("3+sqrt(5)+pow(3,2)+log(5)", 0));
    return 0;
}

I know that embedding Python into C++ can do that

You could do that, but you'd be pulling in a huge dependency to solve a simple problem.

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

muParserX is another C++ mathematical expression parser.

查看更多
登录 后发表回答