Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExprTk: Does an expression has to be recompiled when its values change

Tags:

c++

exprtk

I'm creating an expression with exprtk using variables which change constantly.

Do I have to reset and recompile the exprtk::expression using an updated exprtk::symbol_table everytime I change the value of a variable?

Or are the updated values evaluated directly by the existing, compiled expression?

#include <iostream> 
#include <string>
#include "exprtk.hpp"

int main() {
    std::string expression_string = "y := x + 1";

    int x = 1;

    exprtk::symbol_table<int> symbol_table;
    symbol_table.add_variable("x", x);

    exprtk::expression<int> expression;
    expression.register_symbol_table(symbol_table);

    exprtk::parser<int> parser;

    if (!parser.compile(expression_string, expression))
    {
        std::cout << "Compilation error." << std::endl;
        return 1;
    }

    expression.value(); // 1 + 1

    x = 2;
    // Do I have to create a new symbol_table, expression and parse again?

    // Or does the expression evaluate the new value directly?
    expression.value(); // 2 + 1?

    return 0;
}
like image 377
Roi Danton Avatar asked Apr 09 '17 21:04

Roi Danton


1 Answers

exprtk::expression does not have to be recompiled when the values of the variables referenced by exprtk::symbol_table change. expression.value() can be used immediately.

According to the documentation (Section 10 - Components), the actual values of the variables referenced in the symbol table are resolved not until the expression is evaluated. So compiling the same expression with the parser has to happen once only.

std::string expression_string = "x * y + 3";
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);

expression.register_symbol_table(symbol_table);

parser.compile(expression_string,expression);

x = 1.0;
y = 2.0;
expression.value(); // 1 * 2 + 3

x = 3.7;
expression.value(); // 3.7 * 2 + 3

y = -9.0;
expression.value(); // 3.7 * -9 + 3

// 'x * -9 + 3' for x in range of [0,100) in steps of 0.0001
for (x = 0.0; x < 100.0; x += 0.0001)
{
    expression.value(); // x * -9 + 3
}

During the compilation process [..] the element will be embedded within the expression's AST. This allows for the original element to be modified independently of the expression instance [...] the variables are modified as they normally would in a program, and when the expression is evaluated the current values assigned to the variables will be used.

like image 175
Roi Danton Avatar answered Sep 18 '22 13:09

Roi Danton