/src/r-source/src/nmath/rnbinom.c
Line | Count | Source |
1 | | /* |
2 | | * Mathlib : A C Library of Special Functions |
3 | | * Copyright (C) 1998 Ross Ihaka |
4 | | * Copyright (C) 2000--2016 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 | | * https://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. Pages 488 and 543. |
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 | | |
47 | | double rnbinom(double size, double prob) |
48 | 0 | { |
49 | 0 | if(!R_FINITE(prob) || ISNAN(size) || size <= 0 || prob <= 0 || prob > 1) |
50 | | /* prob = 1 is ok, PR#1218 */ |
51 | 0 | ML_WARN_return_NAN; |
52 | 0 | if(!R_FINITE(size)) size = DBL_MAX / 2.; // '/2' to prevent rgamma() returning Inf |
53 | 0 | return (prob == 1) ? 0 : rpois(rgamma(size, (1 - prob) / prob)); |
54 | 0 | } |
55 | | |
56 | | double rnbinom_mu(double size, double mu) |
57 | 0 | { |
58 | 0 | if(!R_FINITE(mu) || ISNAN(size) || size <= 0 || mu < 0) |
59 | 0 | ML_WARN_return_NAN; |
60 | 0 | if(!R_FINITE(size)) size = DBL_MAX / 2.; |
61 | 0 | return (mu == 0) ? 0 : rpois(rgamma(size, mu / size)); |
62 | 0 | } |