gamma_q.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_FWD_SCAL_FUN_GAMMA_Q_HPP
2 #define STAN_MATH_FWD_SCAL_FUN_GAMMA_Q_HPP
3 
4 #include <stan/math/fwd/core.hpp>
5 
7 
8 namespace stan {
9 namespace math {
10 
11 template <typename T>
12 inline fvar<T> gamma_q(const fvar<T>& x1, const fvar<T>& x2) {
14  using boost::math::tgamma;
15  using std::exp;
16  using std::fabs;
17  using std::log;
18  using std::pow;
19 
20  T u = gamma_q(x1.val_, x2.val_);
21 
22  T S = 0;
23  T s = 1;
24  T l = log(x2.val_);
25  T g = tgamma(x1.val_);
26  T dig = digamma(x1.val_);
27 
28  int k = 0;
29  T delta = s / (x1.val_ * x1.val_);
30 
31  while (fabs(delta) > 1e-6) {
32  S += delta;
33  ++k;
34  s *= -x2.val_ / k;
35  delta = s / ((k + x1.val_) * (k + x1.val_));
36  }
37 
38  T der1 = (1.0 - u) * (dig - l) + exp(x1.val_ * l) * S / g;
39  T der2 = -exp(-x2.val_) * pow(x2.val_, x1.val_ - 1.0) / g;
40 
41  return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);
42 }
43 
44 template <typename T>
45 inline fvar<T> gamma_q(const fvar<T>& x1, double x2) {
47  using boost::math::tgamma;
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 
76 template <typename T>
77 inline 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 = boost::math::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
fvar< T > fabs(const fvar< T > &x)
Definition: fabs.hpp:15
#define S(x, n)
double delta
Definition: runWimpSim.h:98
Float_t x1[n_points_granero]
Definition: compare.C:5
constexpr T pow(T x)
Definition: pow.h:75
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:12
const XML_Char * s
Definition: expat.h:262
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10
double e()
Definition: constants.hpp:89
double T
Definition: Xdiff_gwt.C:5
fvar< T > pow(const fvar< T > &x1, const fvar< T > &x2)
Definition: pow.hpp:15
fvar< T > tgamma(const fvar< T > &x)
Definition: tgamma.hpp:20
fvar< T > gamma_q(const fvar< T > &x1, const fvar< T > &x2)
Definition: gamma_q.hpp:12
fvar< T > digamma(const fvar< T > &x)
Definition: digamma.hpp:22