File: stats.h

package info (click to toggle)
ga 5.9.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 18,472 kB
  • sloc: ansic: 192,963; fortran: 53,761; f90: 11,218; cpp: 5,784; makefile: 2,248; sh: 1,945; python: 1,734; perl: 534; csh: 134; asm: 106
file content (70 lines) | stat: -rw-r--r-- 1,415 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
 * @file
 *
 * @author jeff.daily@pnnl.gov
 *
 * Copyright (c) 2015 Battelle Memorial Institute.
 */
#ifndef _STATS_H_
#define _STATS_H_

#include <math.h>

/** http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance */

#ifdef __cplusplus
extern "C" {
#endif

typedef struct stats {
    unsigned long _n;
    double _mean;
    double _M2;
    double _sum;
    double _min;
    double _max;
} stats_t;

static inline void stats_clear(stats_t *stats) {
    stats->_n = 0UL;
    stats->_mean = 0.0;
    stats->_M2 = 0.0;
    stats->_sum = 0.0;
    stats->_min = 0.0;
    stats->_max = 0.0;
}

static inline void stats_sample_value(stats_t *stats, const double x) {
    double delta = 0;

    /* extra stats */
    stats->_sum = stats->_sum + x;
    if (0UL == stats->_n) {
        stats->_min = x;
        stats->_max = x;
    }
    else {
        stats->_min = stats->_min < x ? stats->_min : x;
        stats->_max = stats->_max > x ? stats->_max : x;
    }

    stats->_n = stats->_n + 1UL;
    delta = x - stats->_mean;
    stats->_mean = stats->_mean + delta/stats->_n;
    stats->_M2 = stats->_M2 + delta * (x - stats->_mean);
}

static inline double stats_variance(const stats_t * const stats) {
    return stats->_M2/(stats->_n-1);
}

static inline double stats_stddev(const stats_t * const stats) {
    return sqrt(stats_variance(stats));
}

#ifdef __cplusplus
}
#endif

#endif /* _STATS_H_ */