Automatic Differentiation
 
Loading...
Searching...
No Matches
gamma_q.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_FWD_FUN_GAMMA_Q_HPP
2#define STAN_MATH_FWD_FUN_GAMMA_Q_HPP
3
8#include <cmath>
9
10namespace stan {
11namespace math {
12
13template <typename T>
14inline fvar<T> gamma_q(const fvar<T>& x1, const fvar<T>& x2) {
15 using boost::math::digamma;
16 using std::exp;
17 using std::fabs;
18 using std::log;
19 using std::pow;
20
21 T u = gamma_q(x1.val_, x2.val_);
22
23 T S = 0;
24 T s = 1;
25 T l = log(x2.val_);
26 T g = tgamma(x1.val_);
27 T dig = digamma(x1.val_);
28
29 int k = 0;
30 T delta = s / (x1.val_ * x1.val_);
31
32 while (fabs(delta) > 1e-6) {
33 S += delta;
34 ++k;
35 s *= -x2.val_ / k;
36 delta = s / ((k + x1.val_) * (k + x1.val_));
37 }
38
39 T der1 = (1.0 - u) * (dig - l) + exp(x1.val_ * l) * S / g;
40 T der2 = -exp(-x2.val_) * pow(x2.val_, x1.val_ - 1.0) / g;
41
42 return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);
43}
44
45template <typename T>
46inline fvar<T> gamma_q(const fvar<T>& x1, double x2) {
47 using boost::math::digamma;
48 using std::exp;
49 using std::fabs;
50 using std::log;
51 using std::pow;
52
53 T u = gamma_q(x1.val_, x2);
54
55 T S = 0;
56 double s = 1;
57 double l = log(x2);
58 T g = tgamma(x1.val_);
59 T dig = digamma(x1.val_);
60
61 int k = 0;
62 T delta = s / (x1.val_ * x1.val_);
63
64 while (fabs(delta) > 1e-6) {
65 S += delta;
66 ++k;
67 s *= -x2 / k;
68 delta = s / ((k + x1.val_) * (k + x1.val_));
69 }
70
71 T der1 = (1.0 - u) * (dig - l) + exp(x1.val_ * l) * S / g;
72
73 return fvar<T>(u, x1.d_ * der1);
74}
75
76template <typename T>
77inline fvar<T> gamma_q(double x1, const fvar<T>& x2) {
78 using std::exp;
79 using std::pow;
80
81 T u = gamma_q(x1, x2.val_);
82
83 double g = tgamma(x1);
84
85 T der2 = -exp(-x2.val_) * pow(x2.val_, x1 - 1.0) / g;
86
87 return fvar<T>(u, x2.d_ * der2);
88}
89} // namespace math
90} // namespace stan
91#endif
static constexpr double e()
Return the base of the natural logarithm.
Definition constants.hpp:20
auto pow(const T1 &x1, const T2 &x2)
Definition pow.hpp:32
fvar< T > log(const fvar< T > &x)
Definition log.hpp:15
fvar< T > tgamma(const fvar< T > &x)
Return the result of applying the gamma function to the specified argument.
Definition tgamma.hpp:21
fvar< T > gamma_q(const fvar< T > &x1, const fvar< T > &x2)
Definition gamma_q.hpp:14
fvar< T > digamma(const fvar< T > &x)
Return the derivative of the log gamma function at the specified argument.
Definition digamma.hpp:23
fvar< T > fabs(const fvar< T > &x)
Definition fabs.hpp:15
fvar< T > exp(const fvar< T > &x)
Definition exp.hpp:13
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Scalar val_
The value of this variable.
Definition fvar.hpp:49
Scalar d_
The tangent (derivative) of this variable.
Definition fvar.hpp:61
This template class represents scalars used in forward-mode automatic differentiation,...
Definition fvar.hpp:40