Update all #include directives to the currently preferred style.
[pspp-builds.git] / src / math / trimmed-mean.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2008, 2009, 2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "math/trimmed-mean.h"
20
21 #include <math.h>
22
23 #include "data/val-type.h"
24 #include "libpspp/assertion.h"
25 #include "libpspp/cast.h"
26 #include "math/order-stats.h"
27
28 #include "gl/xalloc.h"
29
30 static void
31 acc (struct statistic *s, const struct ccase *cx UNUSED, double c, double cc, double y)
32 {
33   struct trimmed_mean *tm = UP_CAST (s, struct trimmed_mean, parent.parent);
34   struct order_stats *os = &tm->parent;
35
36   if ( cc > os->k[0].tc && cc < os->k[1].tc)
37       tm->sum += c * y;
38
39   if ( tm->cyk1p1 == SYSMIS && cc >os->k[0].tc)
40       tm->cyk1p1 = c * y;
41 }
42
43 static void
44 destroy (struct statistic *s)
45 {
46   struct trimmed_mean *tm = UP_CAST (s, struct trimmed_mean, parent.parent);
47   struct order_stats *os = &tm->parent;
48   free (os->k);
49   free (tm);
50 }
51
52 struct trimmed_mean *
53 trimmed_mean_create (double W, double tail)
54 {
55   struct trimmed_mean *tm = xzalloc (sizeof (*tm));
56   struct order_stats *os = &tm->parent;
57   struct statistic *stat = &os->parent;
58
59   os->n_k = 2;
60   os->k = xcalloc (sizeof (*os->k), 2);
61
62   assert (tail >= 0);
63   assert (tail <= 1);
64
65   os->k[0].tc = tail * W;
66   os->k[1].tc = W * (1 - tail);
67
68   stat->accumulate = acc;
69   stat->destroy = destroy;
70
71   tm->cyk1p1 = SYSMIS;
72   tm->w = W;
73   tm->tail = tail;
74
75   return tm;
76 }
77
78
79 double
80 trimmed_mean_calculate (const struct trimmed_mean *tm)
81 {
82   const struct order_stats *os = (const struct order_stats *) tm;
83
84   assert (os->cc == tm->w);
85
86   return
87     (
88      (os->k[0].cc_p1 - os->k[0].tc) * os->k[0].y_p1
89      -
90      (os->k[1].cc - os->k[1].tc) * os->k[1].y_p1
91      +
92      tm->sum
93      -
94      tm->cyk1p1
95      )
96     /
97     ( (1.0 - 2 * tm->tail) * tm->w);
98 }