Mister B said:
To avoid reinventing the wheel, I was wondering if anyone knows of
existing software (in C or libraries that could be called from C code on
Linux platform) that implements a Calculation Engine, whereby formulae can
be defined with a number of inputs, and then triggered to produce an
output.
For example:
formula 1: a + b - c
formula 2: a * ( b + c + d ) / 3
formula 3: a * sqrt (b)
Value A uses formula 1 with inputs X, Y, Z
Value B uses formula 3 with inputs M, N
etc
This is not clear; where do the formulae come from? Are they input by the
user, exist in a file (both in text format), or hardcoded in the program
(possibly as text too)?
What determines which formula is applied?
Doing this properly is a lot of work, as you say, but having an attempt
might be a useful exercise, and could make it easier to choose an
appropriate library once the ins and outs are known.
I had a go at something myself; this code has formulae and inputs hardcoded
(this is just user-input and not difficult). I use C for the 'engine', by
generating a short C program to apply the formula. (The new program prints
it's output; normally you'd need a way of getting the result back into the
calling program).
You need to change the line system("run.bat") into something that compiles
and runs the output of this program, on your machine.
In practice, this sort of approach wouldn't use C as the output format, it's
more likely to be a soft language, and one that can be closely integrated
into C (Python or Lua perhaps), so that the result can be picked up via some
interface.
#include <stdio.h>
#include <stdlib.h>
#define outfile "formula.c"
char* formulae[]={
"a+b-c",
"a*(b+c+d)/3",
"a*sqrt(b)"};
double evaluate(char* formula, double* params,int nparams){
FILE* f;
int i;
f=fopen(outfile,"w");
fprintf(f,"#include<stdio.h>\n");
fprintf(f,"#include<stdlib.h>\n");
fprintf(f,"#include<math.h>\n");
fprintf(f,"\n");
fprintf(f,"double eval(");
for (i=0; i<nparams; ++i){
fprintf(f,"double %c",'a'+i);
if (i<(nparams-1)) fprintf(f,",");
}
fprintf(f,") {\n");
fprintf(f,"double x;\n");
fprintf(f,"x=%s;\n",formula);
fprintf(f,"printf(\"Result is: %%f\",x);\n");
fprintf(f,"}\n");
fprintf(f,"\n");
fprintf(f,"int main(void) {\n");
fprintf(f,"eval(");
for (i=0; i<nparams; ++i){
fprintf(f,"%f",params
);
if (i<(nparams-1)) fprintf(f,",");
}
fprintf(f,");\n");
fprintf(f,"}\n");
fclose(f);
return 0.0;
}
int main(void){
double args[]={23,34,18};
evaluate(formulae[0],args,3);
system("run.bat");
}