1#ifndef STAN_MATH_PRIM_FUN_GRAD_REG_INC_GAMMA_HPP
2#define STAN_MATH_PRIM_FUN_GRAD_REG_INC_GAMMA_HPP
51template <
typename T1,
typename T2>
53 double precision = 1
e-6,
54 int max_steps = 1e5) {
61 return std::numeric_limits<TP>::quiet_NaN();
65 if (z >= a && z >= 8) {
68 T1 a_minus_one_minus_k = a - 1;
69 T1 fac = a_minus_one_minus_k;
72 TP delta = dfac / zpow;
74 for (
int k = 1; k < 10; ++k) {
75 a_minus_one_minus_k -= 1;
80 dfac = a_minus_one_minus_k * dfac + fac;
81 fac *= a_minus_one_minus_k;
89 return gamma_q(a, z) * (l - dig) +
exp(-z + (a - 1) * l) * S / g;
97 for (
int k = 1; k <= max_steps; ++k) {
98 S += s_sign >= 0.0 ?
exp(log_delta) : -
exp(log_delta);
99 log_s += log_z -
log(k);
105 if (log_delta <=
log(precision)) {
106 return gamma_p(a, z) * (dig - l) +
exp(a * l) * S / g;
110 "grad_reg_inc_gamma",
"k (internal counter)", max_steps,
"exceeded ",
111 " iterations, gamma function gradient did not converge.");
typename return_type< Ts... >::type return_type_t
Convenience type for the return type of the specified template parameters.
fvar< T > multiply_log(const fvar< T > &x1, const fvar< T > &x2)
static constexpr double e()
Return the base of the natural logarithm.
fvar< T > log(const fvar< T > &x)
void throw_domain_error(const char *function, const char *name, const T &y, const char *msg1, const char *msg2)
Throw a domain error with a consistently formatted message.
return_type_t< T1, T2 > grad_reg_inc_gamma(T1 a, T2 z, T1 g, T1 dig, double precision=1e-6, int max_steps=1e5)
Gradient of the regularized incomplete gamma functions igamma(a, z)
fvar< T > gamma_p(const fvar< T > &x1, const fvar< T > &x2)
int is_inf(const fvar< T > &x)
Returns 1 if the input's value is infinite and 0 otherwise.
bool is_any_nan(const T &x)
Returns true if the input is NaN and false otherwise.
fvar< T > gamma_q(const fvar< T > &x1, const fvar< T > &x2)
static constexpr double INFTY
Positive infinity.
fvar< T > exp(const fvar< T > &x)
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...