Created
July 16, 2018 23:33
-
-
Save chris-b1/95074cc4d3736d8b32cf1a9b7546d4b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
struct Array { | |
int len; | |
double* values; | |
}; | |
static inline void add_var(double val, double *nobs, double *mean_x, double *ssqdm_x) { | |
double delta; | |
int check; | |
check = ((val == val) != 0); | |
if (check) { | |
nobs[0] = nobs[0] + 1; | |
delta = val - mean_x[0]; | |
mean_x[0] = mean_x[0] + delta / nobs[0]; | |
ssqdm_x[0] = ssqdm_x[0] + ((nobs[0] - 1) * pow(delta, 2)) / nobs[0]; | |
} | |
} | |
static inline double calc_var(int minp, int ddof, double nobs, double ssqdm_x) { | |
double result; | |
if ((nobs >= minp) && (nobs > ddof)) { | |
if (nobs == 1) { | |
result = 0; | |
} | |
else { | |
result = ssqdm_x / (nobs - (double)ddof); | |
} | |
} | |
return result; | |
} | |
Array roll_var(Array input) { | |
double mean_x = 0, ssqdm_x = 0, nobs = 0; | |
int ddof = 1, minp = 1; | |
Array output; | |
output.len = input.len; | |
output.values = (double*)malloc(sizeof(double) * output.len); | |
for (int i = 0; i < input.len; ++i) { | |
add_var(input.values[i], &nobs, &mean_x, &ssqdm_x); | |
output.values[i] = calc_var(minp, ddof, nobs, ssqdm_x); | |
} | |
return output; | |
} | |
int main() { | |
Array input; | |
input.len = 5; | |
input.values = (double*)malloc(sizeof(double) * 5); | |
input.values[0] = 1.1; | |
input.values[1] = 2.1; | |
input.values[2] = 3.1; | |
input.values[3] = 4.1; | |
input.values[4] = 5.1; | |
Array ans = roll_var(input); | |
for (int i = 0; i < ans.len; ++i) { | |
printf("%f\n", ans.values[i]); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment