Custom interpreter for mathematical expressions

Viewed 1512

I have to evaluate a large number of expressions containing variables and I am thinking about writing a small custom interpreter to keep compilation fast and small. However I have no experience with this topic and have a few questions.

Say we have a file with mathematical expressions and a limited set of objects. The file could look like:

expr[x,y,z] = 2*x*y + x^2 + 28/14*z*(x*y^2 + 15*z) + ...

I'd like to parse this somehow so I can evaluate the expressions numerically in my application by simply calling a function expr(float x, float y, float z). The number of parameters should not be fixed (EDIT -: every expression would have its own definition with the appropriate number of parameters or would accept an array) and nesting of parenthesis should be allowed to keep the input files reasonably small.

Since the expressions are all of polynomial type, I can think of how the data structure should look like, but parsing looks difficult. I have already found some answers to somewhat similar questions here on SO, for instance using Lua.

The biggest question, however, is what the performance penalty would be when creating and calling those objects as compared to directly compile these expressions from automatically generated C code.

Thanks in advance!


EDIT -: Please consider the example of expr() above only as such. I guess the best way would be to have objects of a template class that holds coefficients and powers of the variables in sparse arrays.

3 Answers
Related