1#ifndef STAN_MATH_PRIM_FUN_GRAD_REG_INC_GAMMA_HPP
2#define STAN_MATH_PRIM_FUN_GRAD_REG_INC_GAMMA_HPP
49template <
typename T1,
typename T2>
51 double precision = 1
e-6,
52 int max_steps = 1e5) {
59 return std::numeric_limits<TP>::quiet_NaN();
63 if (z >= a && z >= 8) {
66 T1 a_minus_one_minus_k = a - 1;
67 T1 fac = a_minus_one_minus_k;
70 TP delta = dfac / zpow;
72 for (
int k = 1; k < 10; ++k) {
73 a_minus_one_minus_k -= 1;
78 dfac = a_minus_one_minus_k * dfac + fac;
79 fac *= a_minus_one_minus_k;
87 return gamma_q(a, z) * (l - dig) +
exp(-z + (a - 1) * l) * S / g;
95 for (
int k = 1; k <= max_steps; ++k) {
96 S += s_sign >= 0.0 ?
exp(log_delta) : -
exp(log_delta);
97 log_s += log_z -
log(k);
103 if (log_delta <=
log(precision)) {
104 return gamma_p(a, z) * (dig - l) +
exp(a * l) * S / g;
108 "grad_reg_inc_gamma",
"k (internal counter)", max_steps,
"exceeded ",
109 " 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.
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.
fvar< T > lmultiply(const fvar< T > &x1, const fvar< T > &x2)
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 ...