
Fast Mean-Parameterized Negative-Binomial Density, Vectorized (C++ Backend)
Source:R/RcppExports.R
fast_dnbinom_mu_vec_cpp.RdComputes the negative-binomial probability mass function, in its
mean/dispersion parameterization,
$$f(x; \mathrm{size}, \mu) = \binom{x + \mathrm{size} - 1}{x} \left(\frac{\mathrm{size}}{\mathrm{size} + \mu}\right)^{\mathrm{size}} \left(\frac{\mu}{\mathrm{size} + \mu}\right)^{x},$$
elementwise over x, with \(E[X] = \mu\) and
\(\mathrm{Var}(X) = \mu + \mu^2/\mathrm{size}\) (size is the
dispersion/shape parameter; smaller size means more overdispersion
relative to Poisson). This matches R::dnbinom_mu(x, size, mu, give_log)
semantics exactly, but evaluates the three required lgamma calls per
observation via fast_lgamma_vec_cpp's kernel instead of R's own
lgamma dispatch, making it faster than base R's
stats::dnbinom(x, size, mu = mu, log = ...) — measured at 1.35x on
a length-5000 vector (see the
"Utility
/ Math Kernel Performance" benchmark report) — while returning
numerically identical values. Used internally inside the package's
negative-binomial regression likelihood, score, and Hessian kernels.
Arguments
- x
Numeric vector of non-negative integer counts (non-integer or negative values are not validated by this function and will produce incorrect or non-finite results, matching
R::dnbinom_mu's own lack of input validation at the C level).- size
Dispersion (shape) parameter \(> 0\) (single value, recycled against every element of
x).- mu
Mean parameter \(> 0\) (single value, recycled against every element of
x).- return_log
Logical. If
TRUE, return the log-density instead of the density.
References
Negative
binomial distribution for the mean/dispersion parameterization used here.
Analogous Python API:
SciPy stats
distributions index (scipy.stats.nbinom, in its
number-of-successes/probability parameterization — convert via
\(p = \mathrm{size}/(\mathrm{size}+\mu)\)).
See also
fast_lgamma_vec_cpp, whose kernel this function calls
three times per observation.