cpp开源数学表达式解析库exprtk的使用

⌚Time: 2022-07-29 10:49:11

👨‍💻Author: Jack Ge

C++数学表达式工具包库(ExprTk)是一个简单的易于使用,易于集成,运行时极为高效数学表达式解析和求值引擎。解析引擎支持多种形式的功能和逻辑处理语义,易于扩展。

ExprTk表达式计算器支持以下基本功能算术运算、函数和过程:


(00)类型:Scalar, Vector, String

(01)基本运算符:+, -, *, /, %, ^

(02)赋值:=, +=, -=, *=, /=, %=

(03)等式&不等式:=, ==, <>, !=, <, <=, >, >=

(04)逻辑运算符:and, mand, mor, nand, nor, not, or, shl, shr,

                       xnor, xor, true, false

(05)功能:abs, avg, ceil, clamp, equal, erf, erfc,  exp,

                       expm1, floor, frac,  log, log10, log1p,  log2,

                       logn, max,  min, mul,  ncdf,  not_equal, root,

                       round, roundn, sgn, sqrt, sum, swap, trunc

(06)三角学:acos, acosh, asin, asinh, atan, atanh,  atan2,

                       cos,  cosh, cot,  csc, sec,  sin, sinc,  sinh,

                       tan, tanh, hypot, rad2deg, deg2grad,  deg2rad,

                       grad2deg

(07)控制结构:if-then-else, ternary conditional, switch-case,

                       return-statement



(08)循环语句:while, for, repeat-until, break, continue

(09)字符串处理:in, like, ilike, concatenation

(10) 优化:constant-folding, simple strength reduction and

                       dead code elimination

(11) 微积分:numerical integration and differentiation

项目地址:

https://github.com/ArashPartow/exprtk


使用方法:

项目中包含exprtk.hpp文件并使用就可以了

测试代码:


#include <iostream>

#include "exprtk.hpp"

using namespace std;

double eval(string strExpr)

{

    exprtk::expression<double> expr;

    exprtk::parser<double> psr;

    psr.compile(strExpr,expr);

    return expr.value();

}

int main(int argc,char* argv[])

{

    if(argc!=2)

    {

        cout<<"Usage:"<<argv[0]<<" \"expression\""<<endl;

        return -1;

    }

    cout<<argv[1]<<"="<<eval(argv[1])<<endl;

     

    return 0;

}

结果:


s@debian:~/Downloads# ./a.out  "sqrt(2)+log(5)*exp(2)+64/(33-18)"

sqrt(2)+log(5)*exp(2)+64/(33-18)=17.5731

s@debian:~/Downloads# ./a.out  "max(4,5,6)-min(7,8,9)"

max(4,5,6)-min(7,8,9)=-1



exprtk有很明显的缺点: