You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.1 KiB
C

#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
#include <math.h>
#include <values.h>
double mean(double set[], int set_n) {
double sum = 0.0;
for (int i=0; i<set_n; i++) {
sum += set[i];
}
return sum/set_n;
}
bool isalmost(double x, double c, double epsilon) {
assert(epsilon >= 0.0);
return fabs(x-c) < epsilon;
}
double sample_variance(double set[], int set_n) {
double m = mean(set, set_n);
double ss = 0.0;
for (int i=0; i<set_n; i++) {
ss += pow((set[i]-m), 2.0);
}
// Divide by (n-1), as this is *sample* variance (Bessel's correction).
assert(set_n>1);
ss /= (set_n-1);
return ss;
}
double sample_stddev(double set[], int set_n) {
return sqrt(sample_variance(set, set_n));
}
double set_min(double set[], int set_n) {
double min = MAXDOUBLE;
for (int i=0; i<set_n; i++) {
min=fmin(set[i], min);
}
return min;
}
double set_max(double set[], int set_n) {
double max = MINDOUBLE;
for (int i=0; i<set_n; i++) {
max=fmax(set[i], max);
}
return max;
}
double range(double set[], int set_n) {
return set_max(set, set_n) - set_min(set, set_n);
}
int main() {
// Some data
double d[] = {7, 8, 5, 1, 6, 2};
const int d_n = 6;
double e[] = {-10, 0, 10, 11, 12, 13, 14, 8, 9, 10, 11, 10, 10};
const int e_n = 13;
// Some tests
assert(isalmost(mean(d, d_n), 4.833, 0.001));
assert(isalmost(mean(e, e_n), 8.307, 0.001));
// XXX assert(isalmost(median(d, d_n), 5.5, 0.001));
// XXX assert(isalmost(median(e, e_n), XXX, 0.001));
assert(isalmost(sample_variance(d, d_n), 7.766, 0.001));
assert(isalmost(sample_variance(e, e_n), 41.564, 0.001));
assert(isalmost(sample_stddev(d, d_n), 2.787, 0.001));
assert(isalmost(sample_stddev(e, e_n), 6.447, 0.001));
assert(isalmost(set_min(d, d_n), 1.0, 0.001));
assert(isalmost(set_max(d, d_n), 8.0, 0.001));
assert(isalmost(set_min(e, e_n), -10.0, 0.001));
assert(isalmost(set_max(e, e_n), +14.0, 0.001));
assert(isalmost(range(d, d_n), 7.0, 0.001));
assert(isalmost(range(e, e_n), 24.0, 0.001));
// XXX Mode
// XXX Percentile
}