1 /*
2 * Mathlib : A C Library of Special Functions
3 * Copyright (C) 1998 Ross Ihaka
4 * Copyright (C) 2000--2006 The R Core Team
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, a copy is available at
18 * http://www.r-project.org/Licenses/
19 *
20 * SYNOPSIS
21 *
22 * #include <Rmath.h>
23 * double rnbinom(double n, double p)
24 *
25 * DESCRIPTION
26 *
27 * Random variates from the negative binomial distribution.
28 *
29 * NOTES
30 *
31 * x = the number of failures before the n-th success
32 *
33 * REFERENCE
34 *
35 * Devroye, L. (1986).
36 * Non-Uniform Random Variate Generation.
37 * New York:Springer-Verlag. Page 480.
38 *
39 * METHOD
40 *
41 * Generate lambda as gamma with shape parameter n and scale
42 * parameter p/(1-p). Return a Poisson deviate with mean lambda.
43 */
44
45 #include "nmath.h"
46
rnbinom(double size,double prob)47 double rnbinom(double size, double prob)
48 {
49 if(!R_FINITE(size) || !R_FINITE(prob) || size <= 0 || prob <= 0 || prob > 1)
50 /* prob = 1 is ok, PR#1218 */
51 ML_ERR_return_NAN;
52 return (prob == 1) ? 0 : rpois(rgamma(size, (1 - prob) / prob));
53 }
54
rnbinom_mu(double size,double mu)55 double rnbinom_mu(double size, double mu)
56 {
57 if(!R_FINITE(size) || !R_FINITE(mu) || size <= 0 || mu < 0)
58 ML_ERR_return_NAN;
59 return (mu == 0) ? 0 : rpois(rgamma(size, mu / size));
60 }
61