22ab45210c38c98066eb4bb654663114cb496ddd
[pspp-builds.git] / src / math / tukey-hinges.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2008, 2009 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 "tukey-hinges.h"
19 #include <math/order-stats.h>
20
21 #include <gl/xalloc.h>
22 #include <libpspp/assertion.h>
23 #include <libpspp/cast.h>
24 #include <math.h>
25
26 void
27 tukey_hinges_calculate (const struct tukey_hinges *th, double hinge[3])
28 {
29   double a[3];
30   double a_star[3];
31   int i;
32   const struct order_stats *os = &th->parent;
33
34   for (i = 0 ; i < 3 ; ++i)
35     {
36       a_star[i] = os->k[i].tc - os->k[i].cc;
37       a[i] = a_star[i] / os->k[i].c_p1;
38
39       if (a_star[i] < 1)
40         {
41           if (os->k[i].c_p1 >= 1 )
42             {
43               hinge[i] = (1 - a_star[i]) * os->k[i].y
44                 + a_star[i] * os->k[i].y_p1;
45             }
46           else
47             {
48               hinge[i] = (1 - a[i]) * os->k[i].y
49                 + a[i] * os->k[i].y_p1;
50             }
51         }
52       else
53         {
54           hinge[i] = os->k[i].y_p1;
55         }
56
57     }
58 }
59
60 static void
61 destroy (struct statistic *s)
62 {
63   struct tukey_hinges *th = UP_CAST (s, struct tukey_hinges, parent.parent);
64   struct order_stats *os = &th->parent;
65
66   free (os->k);
67   free (s);
68 };
69
70 struct tukey_hinges *
71 tukey_hinges_create (double W, double c_min)
72 {
73   double d;
74   struct tukey_hinges *th = xzalloc (sizeof (*th));
75   struct order_stats *os = &th->parent;
76   struct statistic *stat = &os->parent;
77
78   assert (c_min >= 0);
79
80   os->n_k = 3;
81   os->k = xcalloc (sizeof (*os->k), 3);
82
83   if ( c_min >= 1.0)
84     {
85       d = floor ((W + 3) / 2.0) / 2.0;
86
87       os->k[0].tc = d;
88       os->k[1].tc = W/2.0 + 0.5;
89       os->k[2].tc = W + 1 - d;
90     }
91   else
92     {
93       d = floor ((W/c_min + 3.0)/ 2.0) / 2.0 ;
94       os->k[0].tc = d * c_min;
95       os->k[1].tc = (W + c_min) / 2.0;
96       os->k[2].tc = W + c_min * (1 - d);
97     }
98
99
100   stat->destroy = destroy;
101
102   return th;
103 }