3 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 #include <gsl/gsl_errno.h>
23 #include <gsl/gsl_histogram.h>
28 gsl_histogram_pdf_sample (const gsl_histogram_pdf * p, double r)
33 /* Wrap the exclusive top of the bin down to the inclusive bottom of
34 the bin. Since this is a single point it should not affect the
42 status = find (p->n, p->sum, r, &i);
46 GSL_ERROR_VAL ("cannot find r in cumulative pdf", GSL_EDOM, 0);
50 double delta = (r - p->sum[i]) / (p->sum[i + 1] - p->sum[i]);
51 double x = p->range[i] + delta * (p->range[i + 1] - p->range[i]);
57 gsl_histogram_pdf_alloc (const size_t n)
63 GSL_ERROR_VAL ("histogram pdf length n must be positive integer",
67 p = (gsl_histogram_pdf *) malloc (sizeof (gsl_histogram_pdf));
71 GSL_ERROR_VAL ("failed to allocate space for histogram pdf struct",
75 p->range = (double *) malloc ((n + 1) * sizeof (double));
79 free (p); /* exception in constructor, avoid memory leak */
81 GSL_ERROR_VAL ("failed to allocate space for histogram pdf ranges",
85 p->sum = (double *) malloc ((n + 1) * sizeof (double));
90 free (p); /* exception in constructor, avoid memory leak */
92 GSL_ERROR_VAL ("failed to allocate space for histogram pdf sums",
102 gsl_histogram_pdf_init (gsl_histogram_pdf * p, const gsl_histogram * h)
109 GSL_ERROR ("histogram length must match pdf length", GSL_EINVAL);
112 for (i = 0; i < n; i++)
116 GSL_ERROR ("histogram bins must be non-negative to compute"
117 "a probability distribution", GSL_EDOM);
121 for (i = 0; i < n + 1; i++)
123 p->range[i] = h->range[i];
127 double mean = 0, sum = 0;
129 for (i = 0; i < n; i++)
131 mean += (h->bin[i] - mean) / ((double) (i + 1));
136 for (i = 0; i < n; i++)
138 sum += (h->bin[i] / mean) / n;
148 gsl_histogram_pdf_free (gsl_histogram_pdf * p)