Coverage Report

Created: 2026-11-30 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/r-source/src/nmath/dgamma.c
Line
Count
Source
1
/*
2
 *  AUTHOR
3
 *    Catherine Loader, catherine@research.bell-labs.com.
4
 *    October 23, 2000.
5
 *
6
 *  Merge in to R:
7
 *  Copyright (C) 2000-2019 The R Core Team
8
 *  Copyright (C) 2004-2019 The R Foundation
9
 *
10
 *  This program is free software; you can redistribute it and/or modify
11
 *  it under the terms of the GNU General Public License as published by
12
 *  the Free Software Foundation; either version 2 of the License, or
13
 *  (at your option) any later version.
14
 *
15
 *  This program is distributed in the hope that it will be useful,
16
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 *  GNU General Public License for more details.
19
 *
20
 *  You should have received a copy of the GNU General Public License
21
 *  along with this program; if not, a copy is available at
22
 *  https://www.R-project.org/Licenses/
23
 *
24
 *
25
 * DESCRIPTION
26
 *
27
 *   Computes the density of the gamma distribution,
28
 *
29
 *                   1/s (x/s)^{a-1} exp(-x/s)
30
 *        p(x;a,s) = -----------------------
31
 *                            (a-1)!
32
 *
33
 *   where 's' is the scale (= 1/lambda in other parametrizations)
34
 *     and 'a' is the shape parameter ( = alpha in other contexts).
35
 *
36
 * The old (R 1.1.1) version of the code is available via '#define D_non_pois'
37
 */
38
39
#include "nmath.h"
40
#include "dpq.h"
41
42
double dgamma(double x, double shape, double scale, int give_log)
43
12.2k
{
44
12.2k
#ifdef IEEE_754
45
12.2k
    if (ISNAN(x) || ISNAN(shape) || ISNAN(scale))
46
3.48k
        return x + shape + scale;
47
8.76k
#endif
48
8.76k
    if (shape < 0 || scale <= 0) ML_WARN_return_NAN;
49
8.63k
    if (x < 0)
50
160
  return R_D__0;
51
8.47k
    if (shape == 0) /* point mass at 0 */
52
222
  return (x == 0)? ML_POSINF : R_D__0;
53
8.25k
    if (x == 0) {
54
498
  if (shape < 1) return ML_POSINF;
55
429
  if (shape > 1) return R_D__0;
56
  /* else */
57
153
  return give_log ? -log(scale) : 1 / scale;
58
429
    }
59
60
7.75k
    double pr;
61
7.75k
    if (shape < 1) {
62
3.93k
  pr = dpois_raw(shape, x/scale, give_log);
63
3.93k
  return (
64
3.93k
      give_log/* NB: currently *always*  shape/x > 0  if shape < 1:
65
         * -- overflow to Inf happens, but underflow to 0 does NOT : */
66
3.93k
      ? pr + (R_FINITE(shape/x)
67
3.37k
        ? log(shape/x)
68
3.37k
        : /* shape/x overflows to +Inf */ log(shape) - log(x))
69
3.93k
      : pr*shape / x);
70
3.93k
    }
71
    /* else  shape >= 1 */
72
3.82k
    pr = dpois_raw(shape-1, x/scale, give_log);
73
3.82k
    return give_log ? pr - log(scale) : pr/scale;
74
7.75k
}