1 /* randist/multinomial.c
3 * Copyright (C) 2002 Gavin E. Crooks <gec@compbio.berkeley.edu>
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_rng.h>
23 #include <gsl/gsl_randist.h>
24 #include <gsl/gsl_sf_gamma.h>
26 /* The multinomial distribution has the form
29 prob(n_1, n_2, ... n_K) = -------------------- p_1 p_2 ... p_K
32 where n_1, n_2, ... n_K are nonnegative integers, sum_{k=1,K} n_k = N,
33 and p = (p_1, p_2, ..., p_K) is a probability distribution.
35 Random variates are generated using the conditional binomial method.
36 This scales well with N and does not require a setup step.
39 C.S. David, The computer generation of multinomial random variates,
40 Comp. Stat. Data Anal. 16 (1993) 205-217
44 gsl_ran_multinomial (const gsl_rng * r, const size_t K,
45 const unsigned int N, const double p[], unsigned int n[])
51 unsigned int sum_n = 0;
53 /* p[k] may contain non-negative weights that do not sum to 1.0.
54 * Even a probability distribution will not exactly sum to 1.0
55 * due to rounding errors.
58 for (k = 0; k < K; k++)
63 for (k = 0; k < K; k++)
67 n[k] = gsl_ran_binomial (r, p[k] / (norm - sum_p), N - sum_n);
82 gsl_ran_multinomial_pdf (const size_t K,
83 const double p[], const unsigned int n[])
85 return exp (gsl_ran_multinomial_lnpdf (K, p, n));
90 gsl_ran_multinomial_lnpdf (const size_t K,
91 const double p[], const unsigned int n[])
98 for (k = 0; k < K; k++)
103 for (k = 0; k < K; k++)
108 log_pdf = gsl_sf_lnfact (N);
110 for (k = 0; k < K; k++)
112 /* Handle case where n[k]==0 and p[k]==0 */
116 log_pdf += log (p[k] / norm) * n[k] - gsl_sf_lnfact (n[k]);