1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2004, 2008, 2009, 2011, 2012 Free Software Foundation, Inc.
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.
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.
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/>. */
19 #include "math/histogram.h"
21 #include <gsl/gsl_histogram.h>
24 #include "libpspp/message.h"
25 #include "libpspp/assertion.h"
26 #include "libpspp/cast.h"
27 #include "math/chart-geometry.h"
30 #define _(msgid) gettext (msgid)
31 #define N_(msgid) msgid
34 #include "gl/xalloc.h"
37 histogram_add (struct histogram *h, double y, double c)
39 struct statistic *stat = &h->parent;
40 stat->accumulate (stat, NULL, c, 0, y);
44 acc (struct statistic *s, const struct ccase *cx UNUSED, double c, double cc UNUSED, double y)
46 struct histogram *hist = UP_CAST (s, struct histogram, parent);
48 gsl_histogram_accumulate (hist->gsl_hist, y, c);
52 destroy (struct statistic *s)
54 struct histogram *h = UP_CAST (s, struct histogram, parent);
55 gsl_histogram_free (h->gsl_hist);
61 histogram_create (double bin_width, double min, double max)
64 struct histogram *h = xmalloc (sizeof *h);
65 struct statistic *stat = &h->parent;
66 double upper_limit, lower_limit;
67 const double half_bin_width = bin_width / 2.0;
69 /* -1 if the lower end of the range contains more unused space
76 msg (MW, _("Not creating histogram because the data contains less than 2 distinct values"));
83 lower_limit = floor (min / half_bin_width) - 1;
84 upper_limit = floor (max / half_bin_width) + 1;
86 if (remainder (min, half_bin_width > remainder (max, half_bin_width)))
91 /* The range must be an EVEN number of half bin_widths */
92 if ( (int)(upper_limit - lower_limit) % 2)
94 /* Extend the range at the end which gives the least unused space */
100 /* Now the other end has more space */
104 /* But the range should be aligned to an ODD number of
105 half bin widths, so that the labels are aesthetically pleasing ones. */
106 if ( (int)lower_limit % 2 == 0)
108 lower_limit += -sparse_end ;
109 upper_limit += -sparse_end ;
112 bins = (upper_limit - lower_limit) / 2.0;
114 /* Force the number of bins to lie in a sensible range */
121 upper_limit *= half_bin_width;
122 lower_limit *= half_bin_width;
124 h->gsl_hist = gsl_histogram_alloc (bins);
126 gsl_histogram_set_ranges_uniform (h->gsl_hist, lower_limit, upper_limit);
128 stat->accumulate = acc;
129 stat->destroy = destroy;