Here is heavily abbreviated (ie not validating user input) C-code for generating weights in a smoothing function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define PERIODS 40
/* function to generate weights */
float *weights (char wf[9], float k, float lambda) {
static float w[PERIODS];
for (int x = 0; x < PERIODS; ++x) {
if (strcmp(wf, "weibull") == 0) { w[x] = pow(x/lambda, k-1) * exp(-pow(x/lambda, k)); }
else if (strcmp(wf, "gompertz") == 0) { w[x] = exp(x/lambda) * exp(-exp(x/lambda)/k); }
else w[x] = pow(x/lambda, k-1) * exp(-x/lambda); // gamma
}
return w;
}
int main (int argc, char *argv[]) {
float k = 1.5;
float lambda = 5;
printf("Argument: %s\n", argv[1]);
float *w = weights((argv[1] != NULL) ? argv[1] : "gamma", k, lambda);
for (int i = 0; i < PERIODS; ++i) printf("Weight %d\t%.4f\n", i, w[i]);
return 0;
}
It works correctly, so calling with ./smooth gamma
, ./smooth weibull
, ./smooth gompertz
or simply ./smooth
all produce correct output.
There is something dissatisfying about float *weights (char wf[9], float k, float lambda)
. How would more seasoned developers define char wf[9]
given that strings are usually defined with pointers rather than a character array?