Working with data scientists I learned how many times a data processing system needs to be refined before optimal results can be achieved. That’s why you should not hardcoding math formulas, expressions, and constants in your code. This is especially true if the calculation data logic is not coded by data scientists.
While working on my last project, I was looking for a method to allow data scientists in my team to change the data calculation logic without forcing me to update code in my Kotlin back-end. The solution was to allow them to define complex math formulas, expressions, and constants in a database (or configuration file), from which I would read and then apply them. First of all, is this possible? And how?
There might be many ways to achieve such a goal, but why don’t use a math expression parser?
Searching online for a good library, I came across mXparser.
mXparser is a super easy, rich, fast and highly flexible math expression parser library (parser and evaluator of mathematical expressions / formulas provided as plain text / string). Software delivers easy to use API for JAVA, Android and C# .NET/MONO (Common Language Specification compliant: F#, Visual Basic, C++/CLI). — mxParser
With this library, if data scientists write mathematical expressions, functions, constants that follow the special mxParser notation, I can load and run them.
// few examples of string equivalent to the math formula notation:
"1+2"
"1+2/3+(4*5-10)"
"2*x+sin(y)"
"int( sqrt(1-x^2), x, -1, 1)"
"sum(n, 1, 100, 1/n^2)"
"C(n,k)"
"fib(n) = iff( n>1, fib(n-1)+fib(n-2); n=1, 1; n=0, 0)"
Thanks to this powerful tool, I was able to separate where the data calculation logic is defined from where it is actually executed, making the architecture loosely coupled. This might seem an insignificant achievement, but it has made the process of updating the data calculation logic much more efficient and reliable. In fact, the data scientists in my team are now free to write math expressions, no longer having to trust me to implement them correctly.
You can use mxParser to define simple expressions, functions (even recursive). It also offers several features, and as well as a huge amount of built-in operators, constants, and math functions.
Visit the MathParser.org-mXparser GitHub account for further reading.
Thanks for reading! I hope that you found this article helpful.