Merge commit 'origin/stable'
[pspp-builds.git] / src / math / trimmed-mean.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2008 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 #include "trimmed-mean.h"
19 #include <math/order-stats.h>
20
21 #include <gl/xalloc.h>
22 #include <libpspp/assertion.h>
23 #include <math.h>
24 #include <data/val-type.h>
25
26
27 static void
28 acc (struct statistic *s, const struct ccase *cx UNUSED, double c, double cc, double y)
29 {
30   struct trimmed_mean *tm = (struct trimmed_mean *) s;
31   struct order_stats *os = (struct order_stats *) s;
32
33   if ( cc > os->k[0].tc && cc < os->k[1].tc)
34       tm->sum += c * y;
35
36   if ( tm->cyk1p1 == SYSMIS && cc >os->k[0].tc)
37       tm->cyk1p1 = c * y;
38 }
39
40 static void
41 destroy (struct statistic *s)
42 {
43   struct order_stats *os = (struct order_stats *) s;
44   free (os->k);
45   free (s);
46 }
47
48 struct statistic *
49 trimmed_mean_create (double W, double tail)
50 {
51   struct trimmed_mean *tm = xzalloc (sizeof (*tm));
52   struct order_stats *os = (struct order_stats *) tm;
53   struct statistic *stat = (struct statistic *) tm;
54
55   os->n_k = 2;
56   os->k = xcalloc (sizeof (*os->k), 2);
57
58   assert (tail >= 0);
59   assert (tail <= 1);
60
61   os->k[0].tc = tail * W;
62   os->k[1].tc = W * (1 - tail);
63
64   stat->accumulate = acc;
65   stat->destroy = destroy;
66
67   tm->cyk1p1 = SYSMIS;
68   tm->w = W;
69   tm->tail = tail;
70
71   return stat;
72 }
73
74
75 double
76 trimmed_mean_calculate (const struct trimmed_mean *tm)
77 {
78   const struct order_stats *os = (const struct order_stats *) tm;
79
80   assert (os->cc == tm->w);
81
82   return
83     (
84      (os->k[0].cc_p1 - os->k[0].tc) * os->k[0].y_p1
85      -
86      (os->k[1].cc - os->k[1].tc) * os->k[1].y_p1
87      +
88      tm->sum
89      -
90      tm->cyk1p1
91      )
92     /
93     ( (1.0 - 2 * tm->tail) * tm->w);
94 }