1#ifndef STAN_MATH_PRIM_FUN_LOWER_REG_INC_GAMMA_HPP
2#define STAN_MATH_PRIM_FUN_LOWER_REG_INC_GAMMA_HPP
109template <
typename T1,
typename T2>
111 double precision = 1
e-10,
112 int max_steps = 1e5) {
121 return std::numeric_limits<TP>::quiet_NaN();
131 if ((a < 0.8 && z > 15.0) || (a < 12.0 && z > 30.0)
145 T1 lgamma_a_plus_1 =
lgamma(a + 1);
146 T1 lgamma_a_plus_n_plus_1 = lgamma_a_plus_1;
149 term =
exp(a_plus_n * log_z - lgamma_a_plus_n_plus_1);
151 if (term <= precision) {
154 if (n >= max_steps) {
156 max_steps,
"exceeded ",
157 " iterations, gamma_p(a,z) gradient (a) "
158 "did not converge.");
161 lgamma_a_plus_n_plus_1 +=
log1p(a_plus_n);
167 TP digammap1 =
digamma(a_plus_n);
168 TP sum_b = digammap1 *
exp(a * log_z - lgamma_a_plus_1);
169 lgamma_a_plus_n_plus_1 = lgamma_a_plus_1 +
log(a_plus_n);
171 digammap1 += 1 / a_plus_n;
172 term =
exp(a_plus_n * log_z - lgamma_a_plus_n_plus_1) * digammap1;
174 if (term <= precision) {
175 return emz * (log_z * sum_a - sum_b);
177 if (n >= max_steps) {
179 max_steps,
"exceeded ",
180 " iterations, gamma_p(a,z) gradient (a) "
181 "did not converge.");
184 lgamma_a_plus_n_plus_1 +=
log1p(a_plus_n);
typename return_type< Ts... >::type return_type_t
Convenience type for the return type of the specified template parameters.
double value_of_rec(const fvar< T > &v)
Return the value of the specified variable.
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 > sqrt(const fvar< T > &x)
fvar< T > log1p(const fvar< T > &x)
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 > lgamma(const fvar< T > &x)
Return the natural logarithm of the gamma function applied to the specified argument.
fvar< T > tgamma(const fvar< T > &x)
Return the result of applying the gamma function to the specified argument.
bool is_any_nan(const T &x)
Returns true if the input is NaN and false otherwise.
return_type_t< T1, T2 > grad_reg_lower_inc_gamma(const T1 &a, const T2 &z, double precision=1e-10, int max_steps=1e5)
Computes the gradient of the lower regularized incomplete gamma function.
void check_positive_finite(const char *function, const char *name, const T_y &y)
Check if y is positive and finite.
fvar< T > digamma(const fvar< T > &x)
Return the derivative of the log gamma function at the specified argument.
fvar< T > exp(const fvar< T > &x)
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...