Python example: mrpt_expr_example.py
Compiles and evaluates math formulas with variables at runtime with mrpt.expr.
Modules: mrpt.expr
1#!/usr/bin/env python3
2"""
3Compiles and evaluates math formulas with variables at runtime with mrpt.expr.
4"""
5
6import mrpt.expr
7
8
9def main():
10 # 1. Basic Expression Evaluation
11 # ---------------------------------------------------------
12 expr = mrpt.expr.CRuntimeCompiledExpression()
13
14 # We can pass variables as a dictionary
15 variables = {"x": 10.0, "y": 5.5}
16
17 formula = "x * sin(PI / 2) + y^2"
18 print(f"Compiling: {formula}")
19
20 expr.compile(formula, variables)
21
22 if expr.is_compiled():
23 result = expr.eval()
24 print(f"Result: {result}") # Expected: 10 * 1 + 5.5^2 = 40.25
25
26 # 2. Using Custom Python Functions in the Formula
27 # ---------------------------------------------------------
28 print("\nRegistering custom Python function...")
29
30 # Define a custom Python function
31 def my_custom_logic(a, b):
32 # This could be any complex Python logic
33 return (a + b) / 2.0
34
35 expr_custom = mrpt.expr.CRuntimeCompiledExpression()
36
37 # Register it! Now the parser knows 'my_avg(a,b)'
38 # (names of exprtk built-in functions, like 'avg', are not allowed)
39 expr_custom.register_function("my_avg", my_custom_logic)
40
41 expr_custom.compile("my_avg(10, 20) + 5")
42 print(f"Custom result: {expr_custom.eval()}") # Expected: 15 + 5 = 20.0
43
44 # 3. Dynamic Updates
45 # ---------------------------------------------------------
46 # Note: To update variable values in this specific C++ API,
47 # you re-compile the expression with the new values.
48 # Because compilation is extremely fast (μs), this is standard.
49 new_vars = {"x": 20.0, "y": 2.0}
50 expr.compile(formula, new_vars)
51 print(f"Updated result: {expr.eval()}") # Expected: 20 * 1 + 2^2 = 24
52
53
54if __name__ == "__main__":
55 main()